如何制作类的ArrayList? [英] How to make an ArrayList of Classes?
问题描述
如何将一堆类添加到 ArrayList
,然后从 检索类(派生自,但不是
并使用它来生成检索到的实际类的新对象(即不是 MyBaseClass
)ArrayListMyBaseClass
,因为它是抽象的)
How can I add a bunch of classes to an ArrayList<MyBaseClass>
and then later retrieve a Class (derived from, but not MyBaseClass
) from the ArrayList
and use it to generate a new object of the actual Class retrieved (i.e. not MyBaseClass
since that is abstract)
所有需要添加的类都来自同一个抽象基类(MyBaseClass
)
All classes that need to be added all derive from the same abstract base Class (MyBaseClass
)
我真的想不出另一种方式来实现我想做的事情,所以希望这是可能的......?
I can't really think of another way to achieve what I want to do, so hopefully this is possible... ?
推荐答案
为了防止使用反射,您可能正在寻找 抽象工厂模式.这是一个如何使用 Java 8 实现它的简单示例:
To prevent the use of reflection, you are probably looking for the Abstract Factory Pattern. Here is a simple example how to implement it using Java 8:
private void run() {
List<Supplier<MyBaseClass>> factories = Arrays
.asList(Impl1::new, Impl2::new, Impl3::new);
List<MyBaseClass> baseClassInstances = factories.stream()
.map(Supplier::get)
.collect(Collectors.toList());
}
public abstract class MyBaseClass {
}
public class Impl1 extends MyBaseClass {
}
public class Impl2 extends MyBaseClass {
}
public class Impl3 extends MyBaseClass {
}
这篇关于如何制作类的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!