0

我正在尝试编写一个通用方法来从包含位掩码的整数初始化 EnumSet 值。我收到一个我不明白的编译器错误。这是我的代码:

   private <E extends Enum<E>> void setEnumSet( EnumSet<E> es, int iEnum ) {   
      es.clear(); 
      for (E e : E.values()) {   
         if (0 != (iEnum & (1<<e.ordinal()))) {
            es.add(e); 
         }
      }               
   }

编译器错误:

1>Javac...
1>.\wdqapi.java:266: error: cannot find symbol
1>      for (E e : E.values()) { 
1>                  ^
1>  symbol:   method values()
1>  location: class Enum<E>
1>  where E is a type-variable:
1>    E extends Enum<E> declared in method <E>_setEnumSet(EnumSet<E>,int)

是否有一些特殊的语法可以访问 E 的 values() 方法?(我是 Java 菜鸟。)有人可以帮我解决这个编译器错误吗?谢谢。

4

2 回答 2

4

You cannot do operations on generic types directly because at runtime type-erasure replaces all these with Object. Hence, the above code would be doing Object.values() which obviously doesn't work.

The way to do this is to use Class.getEnumConstants()

To do this you need an instance of E of the Class object of E. Again, remember that at runtime type-erasure will remove all references to the generic type.

Try something like:

private <E extends Enum<E>> void setEnumSet(E[] values,
      EnumSet<E> es, int iEnum )

or

private <E extends Enum<E>> void setEnumSet(Class<E> type, 
      EnumSet<E> es, int iEnum )
于 2013-03-05T18:00:43.313 回答
0

作为传入值数组的替代方法,您可以Class<E>EnumSet. 如果集合不为空,请使用set.iterator().next().getDeclaringClass(); 如果集合为空,则EnumSet.complementOf(set)用于获取非空集合,然后像以前一样获取元素并获取其类。(奇怪的是,EnumSet 没有提供直接获取枚举类的方法,尽管必须存储它complementOf才能工作。)

拥有 Class 对象后,请Class.getEnumConstants按照 John B 的答案中所述使用。

于 2014-05-23T14:41:20.503 回答