带有限扩展枚举参数的通用方法 - 无法访问value()方法 [英] Generic Method With Bounded Extends Enum Parameter - Cannot Access values() method

查看:113
本文介绍了带有限扩展枚举参数的通用方法 - 无法访问value()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个通用方法,该方法采用扩展枚举的有限参数。例如,如果我有一个枚举如下:

I would like to write a generic method that takes a bounded parameter that extends Enum. For example, if I have an Enum as follows:

public enum InputFlags{
    ONE (0000001),
    TWO (0000002),
    THREE (00000004);

    public final int value;

    InputFlags(int value){
        this.value = value;
    }
}

然后我可以执行以下操作:

I can then do the following:

for (InputFlags ifg : InputFlags.values()){
            // Do something with ifg
}

但是,如果我尝试在返回参数有界的泛型方法中执行上述操作,则无法访问 values()方法:

However if I try to do the above in a generic method whose return parameter is bounded, I cannot access the values() method:

public static <T extends Enum> T getFlags(int f){
        T.values(); // NOT allowed, even though I have bounded by extending Enum.
}

似乎我无法访问 values() 在通用方法中。这是Enums的特性还是有一种方法?

It seems as though I cannot access values() in the generic method. Is this a peculiarity of Enums or is there a way round this?

推荐答案

values() code>是一个非常奇怪的事情在Java。查看枚举的文档 - values()甚至没有! values()根本不是一个 Enum 的方法。而是将 static 方法称为 values()隐式添加到每个扩展 Enum 。但是一个枚举 values()方法与 values() enum 中的code>方法

values() is a very strange thing in Java. Look in the documentation for Enum - values() isn't even there! values() is not a method of Enum at all. Instead a static method called values() is implicitly added to every class extending Enum. But the values() method for one enum is different from the values() method in another enum.

T扩展枚举意味着如果 t 有类型 T ,您可以调用实例 c c 中的枚举方法。您不能调用静态方法枚举(即使可以,值)不存在!)

The fact that T extends Enum means that if t has type T you can call instance methods from Enum on t. You can't call static methods of Enum (and even if you could, values() doesn't exist anyway!)

values()仅在你知道实际的枚举按名称。当您只有类型参数 T 时,不能使用。

values() is only useful when you know the actual enum by name. It cannot be used when you only have a type parameter T.

解决此问题的方法是传递对象。像这样:

The way around this problem is to pass a Class object. Like this:

public static <T extends Enum<T>> T getFlags(Class<T> clazz, int f){
    T[] array = clazz.getEnumConstants();  // This is how you can get an array.
    Set<T> set = EnumSet.allOf(clazz);     // This is how you can get a Set.     
}

这篇关于带有限扩展枚举参数的通用方法 - 无法访问value()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆