Question

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. 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.

Was it helpful?

Solution

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;
}

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top