I'm trying to dive deep into Java Generics, and I ran into the problem described in the following code example.
public static void test(Object o) { System.out.println("Hello Object!"); } public static void test(Integer i) { System.out.println("Hello Integer!"); } public static <T> void test(Collection<T> col) { for (T item : col) { System.out.println(item.getClass().getSimpleName()); test(item); } } public static void main (String[] args) throws java.lang.Exception { Collection<Integer> ints = new ArrayList<>(); ints.add(1); test(ints); }
Sample output
Integer Hello Object!
All types are obviously known at compile time. As far as I understand, Java contains only one compiled copy of each method (unlike C ++), and since there are no other restrictions in the T parameter, it is forced to call the general implementation of Object.
My question is: is there a way to call the Hello Integer method for integers without overloading the testing method for Collection<Integer> and without checking the runtime check?
source share