创建存储在列表中的 class 个实例

Creating class instances stored in a list

所以我先做一个 ArrayList。 (? 表示我不知道那里应该有什么,请继续阅读)

ArrayList<?> arrayList = new ArrayList<?>();

因此这将存储 class 摘要名称 class Class,例如它可能存储 ExtendedClass1ClassExtended2.

稍后我遍历 ArrayList 并使用存储在 arraylist

中的名称创建新对象
for (int i = 0; i < arrayList.size(); i++) {
    new arrayList.get(i); // Takes the class name and makes new object out of it
}

我该怎么做?

您需要存储 String class 个名称,然后使用反射创建实例,假设您要使用的是反射:

List<String> arrayList = new ArrayList<>();
arrayList.add("fully.qualified.ExtendedClass1");
arrayList.add("fully.qualified.ClassExtended2");

然后,在你的循环中:

for(int i = 0; i < arrayList.size(); i++) {
    Class<?> cls = Class.forName(arrayList.get(i)); //Get class for the name

    Object instance = cls.newInstance();
    ...
}