mercredi 4 mars 2015

Java generics, type erasure and type of a generic member



Java has type erasure and people say that one can't determine the type of a generic object at runtime without hacks. Consider the code below



public class TestClass<T> {

private T genericField;

public TestClass(T genericField) {
this.genericField = genericField;
}

public void printTypeInfo() {
System.out.println("Hi I'm a " + genericField.getClass());
System.out.println("Am I a string? " + (genericField instanceof String));
System.out.println("Am I a long? " + (genericField instanceof Long));
}

public static void main(String [] args) {
TestClass<String> genericString = new TestClass<>("Hello");
TestClass<Long> genericLong = new TestClass<>(111111L);
genericString.printTypeInfo();
System.out.println("------------------");
genericLong.printTypeInfo();
}
}


It gives me the following result:



Hi I'm a class java.lang.String
Am I a string? true
Am I a long? false
------------------
Hi I'm a class java.lang.Long
Am I a string? false
Am I a long? true


Seems like type information is readily available at runtime. What am I missing here?




Aucun commentaire:

Enregistrer un commentaire