Reputation: 969
Our issue is like this: We want to pass different enum types to a method and call the values() method on the type.
public enum Testing {
A, B, C, D
}
public enum Retesting {
E, F, G, H
}
public static Object[] getValues(Enum e) {
return e.values(); // ! Compilation Error
}
public static void main(String[] args) {
Testing t = Testing.A;
getValues(t);
}
Does anyone know if how something like this should be achieved or if it's possible at all?
Thank you
Upvotes: 0
Views: 3151
Reputation: 20909
Here is a solution using reflection. But I like @korifey's answer better. :)
@SuppressWarnings("unchecked")
public static <T extends Enum<T>> T[] getValues(Class<T> e) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return (T[]) e.getMethod("values").invoke(null);
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
System.out.println(Arrays.asList(getValues(Testing.class)));
}
Upvotes: 0
Reputation: 115328
Both @korifey and @Matt McHenry are right (+1 to each one). I personally think that in your case korifey's way is preferable.
I just wanted to add that your method signature may be:
getValues(Enum e) { .... }
because all enum
s are ordinary classes that extend class Enum
;
Upvotes: 0