The sample code that had been provided (which I tried to duplicate from memory in the above question, clearly cannot work as intended, since enums themselves cannot be generic.
But depending on what the original poster was trying to accomplish, the below may provide what was being sought, and it does compile and run.
public enum Test {
TEST1(String.class),
TEST2(Object.class),
;
Class clazz;
Test(Class<?> clazz) {
this.clazz = clazz;
}
<T> T getInstance() throws IllegalAccessException, InstantiationException {
return (T)clazz.newInstance();
}
public static void main(String[] args) {
try {
String str = TEST1.getInstance();
Object obj = TEST2.getInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
There are some obvious flaws as written here. Depending on what type you are providing into each enum value, there may not be a no-arg constructor available. It could be made more complex through the use of Objenesis if needed to solve that problem. Also, I "cleverly" made the return type of the method to be a generic , so that it may be assigned without warnings/errors. However, it is totally non-typesafe to do so. You could reverse the assignments without compiler errors:
String str = TEST2.getInstance();
Object obj = TEST1.getInstance();
but you get a runtime ClassCastException.
In any case, I think I have proven that generic methods may be written in enums, and moreso that it is possible to write a single method in the enum that returns a new instance of differing class types, based on the type statically associated with each enum value (just not as a generic parameter of each enum value).