简体   繁体   English

从其Class返回泛型类型的实例

[英]Return an instance of generic type from its Class

My classes are : 我的课程是:

public class Module {}
public class WorkerModule extends Module{}
public class WalkerModule extends Module{}

I have a module factory with a static method to create modules : 我有一个使用静态方法创建模块的模块工厂:

public static Module initializeModule(Class<? extends Module myClass) {
    Module module = null;
    try {
        module = myClass.newInstance();
    } catch (SecurityException e) {
        throw new ModuleException(e);
    } catch (InstantiationException e) {
        throw new ModuleException(e);
    } catch (IllegalAccessException e) {
        throw new ModuleException(e);
    }

    return module;
}

It works, but I would like to improve it by using generic types. 它可以工作,但是我想通过使用泛型类型来改进它。 I still need my method to return an instance of my class parameter, which I want to force to be a child of Module class. 我仍然需要我的方法来返回我的类参数的实例,我想强制将其作为Module类的子代。 I don't know how to change my method's declaration. 我不知道如何更改我的方法的声明。 Maybe something like this: 也许是这样的:

public static <T> T initializeModule(Class<T extends Module myClass) {}

but clearly, it's not that. 但显然,不是那样。

public static <T extends Module> T initializeModule(Class<T> myClass) {
    T module = null;
    try {
        module = myClass.newInstance();
    } catch (SecurityException e) {
        throw new ModuleException(e);
    } catch (InstantiationException e) {
        throw new ModuleException(e);
    } catch (IllegalAccessException e) {
        throw new ModuleException(e);
    }
    return module;
}

that would be something like this: 那将是这样的:

public static <T extends Module> T initializeModule(Class<T> myClass) {
    T module = null;
    try {
        module = myClass.newInstance();
    } catch (SecurityException e) { ...
    } catch (InstantiationException e) { ...
    } catch (IllegalAccessException e) { ...
    }

    return module;
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM