代码之家  ›  专栏  ›  技术社区  ›  Matrx007

创建存储在列表中的类实例

  •  0
  • Matrx007  · 技术社区  · 7 年前

    所以我先做一个 ArrayList . ( ? 意思是我不知道那里应该有什么,继续读下去)

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

    所以这将存储抽象类的类名 Class ,例如,它可以存储 ExtendedClass1 ClassExtended2 .

    后来我重复了一遍 数组列表 并使用存储在 arraylist

    for (int i = 0; i < arrayList.size(); i++) {
        new arrayList.get(i); // Takes the class name and makes new object out of it
    }
    

    我该怎么做呢?

    1 回复  |  直到 7 年前
        1
  •  2
  •   ernest_k Petronella    7 年前

    你需要储存 String 类名,然后使用反射创建实例,假设要使用反射:

    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();
        ...
    }