[英]Java: How to get Values of an Enum Class from an Generic Type Object instance?
I want to create an Enum editor, which takes an Enum type as its generic. 我想创建一个Enum编辑器,它将Enum类型作为其泛型。 E is a generic type, but restricted to be an Enum type.
E是泛型类型,但仅限于Enum类型。 How can I get the values of the Enum class from the instance e?
如何从实例e中获取Enum类的值?
public class ComboBoxEnumEditor<E extends Enum<E>>{
public ComboBoxEnumEditor(E e) {
// how to get values of E from e?
// attemp1:
List values = e.getClass().values();
// attemp2:
List values = ((Enum.class)e.getClass()).values();
// attemp3:
List values = ((Enum.class)e.getClass()).values();
// none of the above works...
}
}
Say I have an Enum 说我有一个枚举
public enum Location {
Default( false, EAttributeLocation.MAIN_TABLE_IF_AVAILABLE ),
Main( false, EAttributeLocation.MAIN_TABLE ),
Overflow( false, EAttributeLocation.OVERFLOW_TABLE ),
Separate( false, EAttributeLocation.SEPARATE_TABLE );
......
}
I want my ComboBoxEnumEditor be able to do 我希望我的ComboBoxEnumEditor能够做到
{
ComboBoxEnumEditor(new Location());
}
Please help, thanks. 请帮忙,谢谢。
It looks like you are looking for (but I may be mistaken) 看起来你在寻找(但我可能会弄错)
Enum[] values = e.getClass().getEnumConstants();
or as mentioned by @pbabcdefp in this answer (big +1 for him) if you would like to have E[]
instead of Enum[]
或者@pbabcdefp在这个答案中提到的(对他来说是大+1)如果你想要
E[]
而不是Enum[]
E[] values = e.getDeclaringClass().getEnumConstants();
Also based on 也基于
...which takes an Enum Class as its generic
......将Enum类作为其通用类
your argument should probably be Class<E> clazz
not E e
itself so you could use it with ComboBoxEnumEditor(Location.class);
你的论证应该是
Class<E> clazz
而不是E e
本身所以你可以将它与ComboBoxEnumEditor(Location.class);
. 。 In that case you could simply use
在这种情况下,你可以简单地使用
E[] values = clazz.getEnumConstants();
E[] arr = e.getDeclaringClass().getEnumConstants();
Short answer... You can't. 简短回答......你做不到。 Doing this is not valid syntax since you can't instantiate an enum:
这样做不是有效的语法,因为您无法实例化枚举:
ComboBoxEnumEditor(new Location());
Instead, you need to pass the class of your enum and change your method signature for that, eg 相反,您需要传递枚举的类并更改方法签名,例如
ComboBoxEnumEditor(Location.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.