看这个:
package test;
public abstract class BaseClass {
public abstract void doSomething();
}
package test;
public class A extends BaseClass {
@Override
public void doSomething() {
// TODO Auto-generated method stub
System.out.println("A");
}
}
package test;
public class GenericFoo<T extends BaseClass>{
public GenericFoo(){
}
private T instance;
public void setType(String type){
// client code call this to set concrete type of T
}
public void doSomething(){
instance.doSomething();
}
public static void main(String s) throws InstantiationException, IllegalAccessException{
GenericFoo<?> obj = GenericFoo.class.newInstance();
obj.setType("A");
// I want it to print "A" on console
obj.doSomething();
}
}
如何实现这一点,我的类只允许使用调用创建实例 class#newInstance()
,但它是输入的。