如何使类的ArrayList? [英] How to make an ArrayList of Classes?
问题描述
我怎么能一堆类添加到的ArrayList< MyBaseClass>
再后来检索类(源自,但不是 MyBaseClass <从
的ArrayList
/ code>),并用它来生成检索(实际类的新对象,即不 MyBaseClass
,因为这是抽象的)
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... ?
推荐答案
要prevent使用反射,你可能寻找的抽象工厂模式。下面是一个简单的例子,如何使用,以实现它的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 {
}
又见<一个href=\"http://stackoverflow.com/questions/36272566/how-should-i-select-which-concrete-implementation-should-be-instantiated-based-o\">How我应该选择哪个具体实施应该根据用户的选择被实例化?
这篇关于如何使类的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!