Ariel Chelsău
Ariel Chelsău

Reputation: 969

How to pass multiple enum types as method arguments and then call common methods on them?

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

Answers (3)

korifey
korifey

Reputation: 3509

Try using:

e.getClass().getEnumConstants()

Upvotes: 7

Matt McHenry
Matt McHenry

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

AlexR
AlexR

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

Upvotes: 0

Related Questions