I was wondering why the following code cannot use the compile-time generic type information to correctly lookup the most specific method overload, instead it always uses the method that is applicable to all potential generic parameters. Is there no way of switching on a generic parameter type at compile time to avoid nasty reflection at runtime?
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class Temp {
class A<T> {
T x;
A(T x) {
this.x = x;
}
String bar = foo(x);
private String foo(Integer i) {
return "Int";
}
private String foo(String i) {
return "String";
}
private <T> String foo(List<T> l) {
return "List";
}
private <T> String foo(T v) {
return "Value";
}
}
@Test
public void IntTest() {
Assert.assertEquals(new A<Integer>(1).bar, "Int");
}
@Test
public void StringTest() {
Assert.assertEquals(new A<String>("A").bar, "String");
}
@Test
public void ListTest() {
Assert.assertEquals(new A<List<String>>(new ArrayList<String>()).bar, "List");
}
@Test
public void LongTest() {
Assert.assertEquals(new A<Long>(1L).bar, "Value");
}
}