P<Cls> p = new P<>();
Remember that Java implements generics by erasing, which means that the constructor for Pdoes not really know what Eis at run time. Java generics are essential to help developers at compile time.
, new P<>() new Date(), - , E. E , P<E>. name - Object, Date. , , , name , , (Cls ), , .
p.name.getClass() ((Cls)p.name).getClass(), .test2() , (extends Cls). , p.name.getClass() ((Cls)p.name).getClass().
:
System.out.println(p.name) System.out.println((Object)p.name), println - , Object.test1(p.name) . T, p.name Object getClass() .
, , :
class P{
Object name = new Date();
}
public static void main(String[] args) {
P p = new P();
System.out.println(p.name);
System.out.println(((Cls)p.name).getClass());
test1(p);
test2(p);
}
public static void test1(P k){
System.out.println(k.name.getClass());
}
public static void test2(P k){
System.out.println(((Cls)k.name).getClass());
}