look at this:
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();
}
}
how to implement this, my class is only allowed to create instance with calling class#newInstance() , but it’s typed.
You cannot set the type of an object at run time; you can only create instances of specific types. Once an instance of
GenericFoohas been created, there’s no way to set it’s type parameter. (Due to type erasure, that doesn’t even make sense at run time anyway.)The best you can do is something like this: