Java Generics - Calling specific methods from typically typed

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?

+5
source share
3 answers

It's impossible. Due to the type of erasure, the type Collection<T> will be allowed to enter Collection<Object> . Erasing Common Methods

+3
source

You can observe the same behavior without generics.

 Object o = new Integer(5); test(o); // will output "Hello Object!" 

Overloaded methods are resolved using information such as compile time, rather than run time. See JLS: https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.9

+2
source

No, you cannot do what you ask for the reasons you gave. The erasure type means that overloading is allowed once for all variables of the type, and it must be allowed for Object.

+1
source

Source: https://habr.com/ru/post/1208517/


All Articles