在泛型上调用 Enum.values()

Calling Enum.values() on a generic type

目标是实现通用枚举转换器。 我知道 Enum1Enum2 具有相同的值和相同的顺序。

目标是实现类似这样的东西:(这有效)

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

但是我有几个枚举,所以我想做一个通用方法:(这行不通)

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

我的问题是在 T.values() 处编译器告诉我:

The method values() is undefined for the type T

你们知道我如何解决这个问题吗?或者你们对我的问题有其他想法吗?

执行此操作的常用方法是传递目标 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()。您可以使用它从目标 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);
        }
    }
}

运行 这会产生以下输出:

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'