关于think in java上的
An interesting thing happens when you use the generic syntax for Class objects: newlnstance( ) will return the exact type of the object, rather than just a basic Object as you saw in ToyTest.java. This is somewhat limited
class Toy{
private String name;
Toy(){}
Toy(int i){}
}
class FancyToy extends Toy{
FancyToy(){
super(1);
}
}
public class GenericToyTest{
public static void main(String...args) throws Exception{
Class<FancyToy> ftClass = FancyToy.class;
FancyToy fancyToy = ftClass.newInstance();
Class<? super FancyToy> up = ftClass.getSuperclass();
// Object.class;
//!Error
//!Class<Toy> up2 = ftClass.getSuperclass();
//!Toy t = up.newInstance();
System.out.println(up.getName());
Object obj = up.newInstance();
}
}
输出结果为 com.company.Toy
- Class<? super FancyToy> up;与Class<Toy> up不是一样的(以后再研究区别)
- Toy t = up.newInstance();//Error
up接受的为:FancyToy的超类
up可以接受Toy.class和Object.class
up.newInstance();自然可能返回Object的实例化或Toy的实例化,是很模糊的。
以后应该会有更深刻的理解
(未完待续)