I have seen it mentioned on some places online that in some situations it is possible to use the reflection API to get back information about generic data types which I thought would be lost through type erasure.
I am looking for complete list of the situations where type erasure is not complete i.e. something is still accessible via reflection. A Good list of examples and associated reflection code that can get at the generic types would be excellent.
UPDATE http://tutorials.jenkov.com/java-reflection/generics.html had exactly the examples I was looking for.
The general idea is that if you create a named or anonymous class that is a subclass of a generic type with particular types for the type parameters, then the subclass is not generic and not subject to type erasure. Assuming that you can get hold of the
Class
object for the subclass, you can use reflection on that object to find out what the parameter types are.When you think about it, this is not really an "exception" to the erasure rule. Rather, it is arranging that the class in question is not generic by explicitly reifying it.
I think it just comes down to this:
No object instance stores any type information.
The classes, however, retain all their generic signatures (otherwise you could not have any generic type checking at compile time)
So, using reflection, you can read the generic type information for a given class.
Example:
Reflection will tell you that this is a List of MyObject (because this information is compiled into the MyList class).
but
Reflection will not tell you anything useful (because the ArrayList class knows nothing about MyObject).