Reputation: 327
Why is the following snippet printing:
Constructor class: class java.lang.Integer
Constructor obj: class java.lang.Integer
I would expect
Constructor class: class java.lang.Integer
Constructor obj: class java.lang.Object
because type erasure "replaces" unbound T with object. (java13 in use)
Thank you.
public class Test {
public static void main(String... args){
var g = new TestG<>(Integer.class, 2);
g.print();
}
}
public class TestG<T> {
private final Class<T> clazz;
private final T obj;
public TestG(Class<T> clazz, T obj) {
this.clazz = clazz;
this.obj = obj;
}
public void print(){
System.out.println("Constructor class: " + clazz);
System.out.println("Constructor obj: " + obj.getClass());
}
}
Upvotes: 0
Views: 47
Reputation: 327
Considering:
Object o = 2;
System.out.println(o.getClass());
one sees that .getClass()
returns the runtime type, which is Integer.
So, this question actually has nothing to do with type erasure.
This answer was given by Sweeper.
Upvotes: 1