0

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

Kevin Welker
  • 7,719
  • 1
  • 40
  • 56
Ariel Chelsău
  • 959
  • 3
  • 9
  • 20
  • 1
    It's not clear what problem you want to solve. Can you explain why you need this? – Puce Mar 13 '12 at 16:30
  • An enum is a *thing*. It has *a* value. – Brian Roach Mar 13 '12 at 16:31
  • 2
    possible duplicate of [Getting all the enum values from enum value](http://stackoverflow.com/questions/2269803/getting-all-the-enum-values-from-enum-value) – Brian Roach Mar 13 '12 at 16:34
  • 1
    It's possible. look at my answer. But `Enum e` here means that `e` is an instance of some enum, say `Testing.A`. Method `getValues(Class extends Enum> e)` would be more correct. Than you could write `e.getEnumConstants()`. – korifey Mar 13 '12 at 16:36
  • @korifey - Your answer is correct; you have to get the values from the class itself. This has already been asked and answered on SO which is why I voted to close as dup. – Brian Roach Mar 13 '12 at 16:38
  • @Brian Roach Yeps, looks like duplicate – korifey Mar 13 '12 at 16:43

3 Answers3

7

Try using:

e.getClass().getEnumConstants()
korifey
  • 3,379
  • 17
  • 17
0

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)));
}
Matt McHenry
  • 20,009
  • 8
  • 65
  • 64
0

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 enums are ordinary classes that extend class Enum;

AlexR
  • 114,158
  • 16
  • 130
  • 208