Java generics are implemented using type erasure. That means that if I have a method:
public void setMapParam(Map<String, Integer> p) { ... }
after compilation, it will end up in the .class as:
public void setMapParam(Map p) { ... }
I have a JAR file with generic classes and methods like the above. It is just the binary. No source code no nothing.
But when I use it in code, Eclipse auto completion gives me setMapParam(Map<String, Integer> p) even though in the binary is like setMapParam(Map p).
How does Eclipse now the type (Map<String, Integer>) even if the method signature has been type erased (to Map)? Or am I missing something?
Type erasure does not mean that the compiled code contains no type parameter information. Type parameters that are used in class and member definitions are present in the compiled code and available via reflection (see
TypeVariable).What type erasure means is that object instances do not have individual type parameters. Given a class definition
MapImpl extends HashMap<T extends Comparable, Integer>and an instance of that class, you cannot find out what specific value ofTwas used in the code that created the instance, because that information does not exist. But you can find out that itextends Comparableand that the value type isInteger, because that information is part of the class definition (and shared by all instances).