Avoiding Erasure

· Java

If you remember my post from yesterday, you'd remember my rant about how generics information is not available in the Class (javadoc) instance.

Well, I've also written something which is wrong: That the information is not found in the .class file. It does, at some level. As far as erasure goes, it will erase all generics information and replace them with the highest bound possible.

However, some bounding information is stored to the .class file, because otherwise it wouldn't know which parameter types to accept. Also, this information is required for the getTypeParameters (javadoc) method.

The simplest solution would be to just create a different Class instance for every different typed parameter set, just like they're creating a different Class instance for every array with a different dimension number and compound type. However, I believe there would be a lot more instances of these differently typed Class instances.

A different solution could be to create another reflector method inside Class - say, a method called Type[] getSpecificTypesFor(T obj) which would return the used types for a specific object. Obviously, that would means saving this information for every Object, but that way a Class instance would always stay the same.

Which is better? And a better question, what kind of a solution would be given to the users?

Comments (1)

Autoboxing Tips at Chaotic Java
[...] Autoboxing, a feature which seems like it had squeezed into JSR 201, is a convenience feature which has its own bag of tricks. This feature seems to come as a complement to the major EoD feature in Tiger, Generics. Since generics can’t be used with primitives as their types (i.e. Can’t declare Collection<int>), their wrappers are used instead (Collection<Integer>). This is due to erasure, as most annoying things about generics are (such as reflection data, an old rant of mine). [...]