如何制作类的ArrayList? [英] How to make an ArrayList of Classes?

查看:22
本文介绍了如何制作类的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一堆类添加到 ArrayList,然后从 检索类(派生自,但不是 MyBaseClass)ArrayList 并使用它来生成检索到的实际类的新对象(即不是 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... ?

推荐答案

为了防止使用反射,您可能正在寻找 抽象工厂模式.这是一个如何使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆