【问题标题】:Using Type Input to Create an Object使用类型输入创建对象
【发布时间】:2020-03-21 10:31:11
【问题描述】:

我无法找到如何做到这一点。有人告诉我 type 和 class 是两个不同的东西,我不知道,但并不让我感到惊讶。当我使用类型变量“M”时,我被告知它期待一个类,而不是一个类型。我愿意以任何方式接受参数。此外,如果有办法获得这些类的数组,那将是最好的。

public <M> void addModule()
{
  Module module = new M(); // This is the error, other stuff shouldn't matter
  module.setStructure(this);
  modules.add(module);
}

【问题讨论】:

标签: java class generics types


【解决方案1】:

类型变量(例如您的示例中的M)是实际类型的占位符。实际类型是在运行时确定的。在您的代码中,编译器不可能知道如何创建 M,因为它不知道它是什么。

你可能需要这样的东西:

interface Module {
    void setStructure(ModuleCollection collection);
}

interface ModuleMaker<T extends Module> {
    T makeModule();
}

class ModuleCollection {
    private final List<Module> modules = new ArrayList<>();

    public void addModule(ModuleMaker<?> maker) {
        Module module = maker.makeModule();
        module.setStructure(this);
        modules.add(module);
    }
}

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 2013-04-11
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2022-11-30
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多