在Java中使用父类名存储时如何返回继承的对象

我正在尝试创建一个助手。我的应用程序可以有许多库,一旦实例化,我想创建一个工厂以便能够跨类共享实例,即:


public ArrayList<Helper> helper = new ArrayList<>(asList(

    new Helper(SomeLib.class, new SomeLib()),

    new Helper(SomeOtherLib.class, new SomeOtherLib())

));

我的图书馆课程目前是测试这项工作的标准。


class Library {

    public Library() { System.out.println("Instance is working"); }

}

我试图开始工作的示例库如下所示:


public class ExampleLib extends Library {

    public void test() { System.out.println("Test OK"); }

}

我当前的 Helper 类看起来像这样,但是,我无法将库强制转换回原来的继承类,我尝试了多种方法:


import dreambot.libs.Library;


public class Helper {

    private Library lib;

    private Class<? extends Library> name;

    

    public Helper(Class<? extends Library> name, Library lib) {

        this.name = name;

        this.lib = lib;

    }

    

    public Class<? extends Library> getName() { return name; }

    public <Library> Library getLib() {

        // All the things I've tried to do

        return (this.name) lib;

        return name.cast(lib);

        return lib.getClass().cast(lib);

    }

}

反过来,我想要的是:


public ArrayList<Helper> helper = new ArrayList<>(asList(

    new Helper(ExampleLib.class, new ExampleLib()),

));


public void test() {

    Arrays.stream(helper.toArray()).filter(c -> c.getName(ExampleLib.class)).getFirst().ifPresent(h -> {

        h.getLib().test(); // Should output "Test OK"

    });

我在 IDE 中收到的错误Helper::getLib是:


不是一个声明return (this.name) lib;


需要不兼容的类型:库,找到:dreambot.libs.Library for return lib.getClass().cast(lib);和return name.cast(lib);


任何帮助,将不胜感激。


温温酱
浏览 106回答 1
1回答

墨色风雨

尝试:import dreambot.libs.Library;public class Helper<T extends Library> {&nbsp; &nbsp; private T lib;&nbsp; &nbsp; private Class<T> name;&nbsp; &nbsp; public Helper(Class<T> name, Library lib) {&nbsp; &nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; &nbsp; &nbsp; this.lib = lib;&nbsp; &nbsp; }&nbsp; &nbsp; public Class<T> getName() { return name; }&nbsp; &nbsp; public T getLib() {&nbsp; &nbsp; &nbsp; &nbsp; return lib;&nbsp; &nbsp; }}甚至更简单:import dreambot.libs.Library;public class Helper<T extends Library> {&nbsp; &nbsp; private T lib;&nbsp; &nbsp; public Helper(Library lib) {&nbsp; &nbsp; &nbsp; &nbsp; this.lib = lib;&nbsp; &nbsp; }&nbsp; &nbsp; public Class<T> getName() { return lib.getClass(); }&nbsp; &nbsp; public T getLib() {&nbsp; &nbsp; &nbsp; &nbsp; return lib;&nbsp; &nbsp; }}并且在调用构造函数时不要忘记钻石运算符:public ArrayList<Helper> helper = new ArrayList<>(asList(&nbsp; &nbsp; new Helper<>(SomeLib.class, new SomeLib()),&nbsp; &nbsp; new Helper<>(SomeOtherLib.class, new SomeOtherLib())));可以简化为:public ArrayList<Helper> helper = new ArrayList<>(asList(&nbsp; &nbsp; new Helper<>(new SomeLib()),&nbsp; &nbsp; new Helper<>(new SomeOtherLib())));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java