Puzzle: Two instances of a class with different methods

Submitted by kofa on Mon, 09/07/2020 - 14:53

OK, some more Java fun. The following will print 'You won'. What arguments (you may modify both!) to check would make the code compile without casting to Class, and still result in 'You won' being printed? (I've used the fully specified name of Arrays so you don't get funny ideas and create a class with that name, adding a static equals method that simply returns false all the time.) Long-time readers of Peter Verhas's blog, https://javax0.wordpress.com/, will be at a definite advantage (true in general, BTW).

public class ClassFun {
    public static void main(String[] args) {
        check((Class) String.class, Object.class);
    }
    private static <T> void check(Class<T> type1, Class<T> type2) {
        if (!java.util.Arrays.equals(type1.getDeclaredMethods(), type2.getDeclaredMethods())) {
            System.out.println("You won");
        }
    }
}

Comments