简体   繁体   English

如何创建一个可以稍后从列表中实例化的类类型数组?

[英]How to create an array of class types that can later be instantiated from the list?

I'll preface this question with the fact that I am not a professional Java programmer. 我将以我不是专业Java程序员的事实开头这个问题。 I come from a strong C embedded systems background, but was self-taught Java back in college. 我来自强大的C嵌入式系统背景,但是上大学时还是自学Java。

I am creating a simple program where there are many different data "producer" classes. 我正在创建一个简单的程序,其中有许多不同的数据“生产者”类。 Each class generates some kind of data output product. 每个类都会生成某种数据输出产品。

ArrayList< Class<? extends OtherClass> > list = new ArrayList< Class<? extends OtherClass> >();

//Register producers based on some criteria for the analysis being done
list.add(Producer1.class);
list.add(Producer2.class);

//Some time later, I want to create instances of those classes and link them to a 'report'
Report report = new Report();
report.addProducer( new list.get(0)() );

Of course, the above code does not work. 当然,上面的代码不起作用。 I am able to create an ArrayList of class types, but I am not able to instantiate them at a later time (at least I am not able to find the correct syntax to do so). 我可以创建一个类类型的ArrayList,但是以后不能实例化它们(至少我找不到这样做的正确语法)。

I also intended originally to do this with interfaces , but the syntax for creating an array of classes does not seem to work like extends in the above code sample. 我本来也打算使用interfaces来完成此interfaces ,但是用于创建类数组的语法似乎不像上述代码示例中的extends那样起作用。 I tried the following, but it failed syntax checking: 我尝试了以下操作,但是语法检查失败:

ArrayList< Class<? implements OtherClass> > list = new ArrayList< Class<? implements OtherClass> >();

I searched around for a suitable answer, but not knowing the correct question/terminology to ask can make that difficult. 我四处寻找合适的答案,但不知道要问的正确问题/术语会令您感到困难。 I found this solution, but their intentions may have been different. 我找到了这个解决方案,但是他们的意图可能有所不同。

Of course, if this can be done in a simpler way then I am open to all suggestions. 当然,如果可以用更简单的方式完成此操作,那么我愿意接受所有建议。

Assuming all the classes in the list have no-arg constructor, you can instantiate them with 假设列表中的所有类都具有no-arg构造函数,则可以使用实例化它们

list.get(0).newInstance()

Also this works just fine for interfaces 而且这对于接口来说也很好

List<Class<? extends SomeInterface>>

Working example 工作实例

The Producer interface: 生产者接口:

public interface Producer {

  void produce();

}

First implementation: 第一次执行:

public class Producer1 implements Producer {

  @Override
  public void produce() {
    System.out.println("Producer 1");
  }
}

Second implementation: 第二实施:

public class Producer2 implements Producer {

  @Override
  public void produce() {
    System.out.println("Producer 2");
  }
}

Report class: 报告类别:

public class Report {

  private final List<Producer> producers = new ArrayList<>();

  public void addProducer(Producer producer) {
    producers.add(producer);
  }

  public void produce() {
    producers.forEach((p) -> p.produce());
  }

}

Running following main method: 运行以下主要方法:

public static void main(String[] args) {
    Report report = new Report();
    List<Class<? extends Producer>> producers = new ArrayList<>();
    producers.add(Producer1.class);
    producers.add(Producer2.class);
    producers.forEach((p) -> {
      try {
        report.addProducer(p.newInstance());
      } catch (InstantiationException | IllegalAccessException ex) {
        System.out.print("Ooops");
      }
    });
    report.produce();
  }

Will output to console: 将输出到控制台:

Producer 1
Producer 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将对象类型的数组存储为字符串,以便另一个类以后可以调用并打印该字符串。 爪哇 - How to store an array of object types as a string so another class can later call and print that string. java 从实例化的基类创建子类? - Create child class from instantiated base class? 如何在抽象类型的java中初始化List,以便稍后可以将子类型添加到列表中 - how to initialize List in java of an abstract type so I can add sub types to the list later 如何存储列表中的多个项目的全局数组供以后使用 - How to store global Array of multiple items from a list for later use 如何确保一个类只能由Spring实例化? - How to ensure a class can only be instantiated by Spring? 实例化后,可以将List分配给其他类的列表吗? - Can a List be somehow assigned to a list of another class after being instantiated? 查找可以实例化的相关类型 - Find related types that can be instantiated class无法实例化 - class can't be instantiated 可以列出 <Character> 被实例化? - can List<Character> be instantiated? 在 Java 中,我能否重用接口参数中的 generics 类型来创建不同的 class,它也需要泛型类型? 如果是这样,怎么办? - In Java, can I reuse the generics types from an interface parameter to create a different class which also requires generic types? And if so, how?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM