You have declared a generic with no upper bound. Replacement for an unbounded generic
is Object
itself
This means, when the class file gets generated your Foo<T>
class looks something like this
class Foo {
private Object t;
public Foo(Object t) throws InstantiationException, IllegalAccessException{
System.out.println("1. T is "+t.getClass());
this.t = (Object)"test";
System.out.println("2. T is "+t.getClass());
}
void fun(){
System.out.println("3. T is "+t.getClass()+" t = "+t);
}
}
This is due to the fact that, generics are only there to ensure compile time type safety . In run-time they are erased
Considering this
this.t = (Object)"test";
is a valid statement, because Object
is super class of all the classes and this.t
then on becomes a String
The reason for 2. T is Still class java.lang.Integer
,
- here
t
is a parameter to the constructor and the parameter still points toInteger
(not overwritten) - and the parameter takes precedence over
this.t