Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - calling specific methods from generic-typed ones

Tags:

java

generics

I try to dive deeply into the Java Generics and I've come across a problem described by the following sample code.

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);
}

The output of the sample is

Integer
Hello Object!

All the types are obviously known at compile time. As far as I understand, Java holds only a single compiled copy of each method (unlike C++) and because no other constraints are given about the parameter T, it's forced to call the generic Object implementation.

My question is - is there any way to call the "Hello Integer" method for integers without overloading the test method for Collection<Integer> and without using runtime type checking?

like image 748
Danstahr Avatar asked Dec 07 '14 03:12

Danstahr


1 Answers

It cannot be done. Due to type erasure type Collection<T> will be resolved to type Collection<Object>. Erasure of Generic Methods

like image 181
michal.z Avatar answered Oct 06 '22 00:10

michal.z