Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Enum.values() on a generic type

The goal is to implement a generic Enum translator. I know Enum1 and Enum2 have the same values and in the same order.

The goal is to implement something like this:(this works)

private static Enum1 translateEnum(Enum2 originalEnum) {
    return Enum1.values()[originalEnum.ordinal()];
}

But I have several enums, so I want to make a generic method: (this doesn't work)

private static < T extends Enum<T>,G extends Enum<G>> T translateEnum(G originalEnum) {
    return T.values()[originalEnum.ordinal()];        
}

My problem is that at T.values() the compiler tells me :

The method values() is undefined for the type T

Do you guys have an idea of how I could solve this issue or do you have any alternative idea to my problem?

like image 758
Gabriel Avatar asked Jul 25 '17 17:07

Gabriel


People also ask

Can enums be generic?

Enum, Interfaces, and GenericsThe enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types.

Can we use .equals for enum?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Can you assign values to enums?

Enum ValuesYou can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.

Is enum allowed in switch case?

We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.


1 Answers

A common way to do this is to pass the target class object (or an object of the target class) as an argument to the function, then use methods from the class object to do the tricky part. For enum classes, the class object has a method which returns the equivalent of Enum.values(). You can use that to get the enum values from the target class:

public class Scratch {
    enum lower { a, b, c };
    enum upper { A, B, C };

    static <T extends Enum<T>> T translate(Enum<?> aFrom, Class<T> aTo) {
        return aTo.getEnumConstants()[aFrom.ordinal()];
    }

    public static void main(String[] args) {
        for (lower ll : lower.values()) {
            upper uu = translate(ll, upper.class);
            System.out.printf("Upper of '%s' is '%s'\n", ll, uu);
        }
        for (upper uu : upper.values()) {
            lower ll = translate(uu, lower.class);
            System.out.printf("Lower of '%s' is '%s'\n", uu, ll);
        }
    }
}

Running this produces the following output:

Upper of 'a' is 'A'
Upper of 'b' is 'B'
Upper of 'c' is 'C'
Lower of 'A' is 'a'
Lower of 'B' is 'b'
Lower of 'C' is 'c'
like image 133
Kenster Avatar answered Sep 29 '22 09:09

Kenster