是否可以声明存储在集合中的类型(文字)变量? 或者这可能更像是一种解释型语言的特性/任务,而不是像 Java 这样的编译型语言?
例如:
import java.util.*;
class Base {}
class A1 extends Base{}
class A2 extends Base{}
public class Test{
public static void main(String[] args){
ArrayList<Class<? extends Base>> typeArrayList=new ArrayList<Class<? extends Base>>();
typeArrayList.add(A1.class);
typeArrayList.add(A2.class);
typeArrayList.add(A1.class);
typeArrayList.add(A1.class);
//etc. etc.
//now that all the types are nicely stored in a collection,
//could we somehow use them to declare variables of those types?
//e.g. declare something like:
//typeArrayList.get(1) someVariable;
}//main
}//Testlass
最佳答案
您可以使用:
Object o = typeVarArrayList.get(1).newInstance();
或
Type o = (Type) typeVarArrayList.get(1).newInstance();
但是你需要类有一个没有参数的构造函数。
如果您需要更具体的构造函数,请参阅 here
关于java - 声明存储在集合中的类型(文字)的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20619304/