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;
}
Return an instance of generic type from its Class
-
11-07-2023 - |
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.
La solution
Autres conseils
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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow