Reputation: 335
I found the following question and answer on the oracle website
What is the following class converted to after type erasure?
public class Pair<K, V> {
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey(); { return key; }
public V getValue(); { return value; }
public void setKey(K key) { this.key = key; }
public void setValue(V value) { this.value = value; }
private K key;
private V value;
}
Answer:
public class Pair {
public Pair(Object key, Object value) {
this.key = key;
this.value = value;
}
public Object getKey() { return key; }
public Object getValue() { return value; }
public void setKey(Object key) { this.key = key; }
public void setValue(Object value) { this.value = value; }
private Object key;
private Object value;
}
But when i decompile the class file using JD-GUI, i still see all the generic types similar what i have in the actual source code.
Does this mean that the generic types are retained in the class file? i'm using Java 6.
The decompiler version of the class using JD-GUI is as follows. I'm using Eclipse Helios to compile the class.
public class Pair<K, V>
{
private K key;
private V value;
public Pair(K key, V value)
{
this.key = key;
this.value = value;
}
public K getKey() {
return this.key; }
public V getValue() { return this.value; }
public void setKey(K key) {
this.key = key; }
public void setValue(V value) { this.value = value;
}
}
Upvotes: 7
Views: 999
Reputation: 65046
Some generic type information is retained in the .class file - enough to allow you to determine, via reflection, that the type Pair is generic, and for classes that have Pair members, what the types of the generic parameters are and so on. The fact that this information is retained forms the basis of techniques like super type tokens that allow you pass around type tokens which retain information about their generic parameters.
Outside of reflection, however, type erasure means that the Pair
class is mostly going to behave as in the stripped version in the "Answer" from the Oracle website. In particular, the actual bytecode for the methods won't have reference to generic types K
or V
- only Object, and the method signatures will accept and return Object
.
In this case, JD-GUI is just being smart and using the information stored in the .class file to restore the generic information in the decompiled output, but rest assure the types are erased in the bytecode.
Upvotes: 7