为什么我不能从Enum对象类中获取.values()? [英] Why I can not get .values() from Enum object class?

查看:159
本文介绍了为什么我不能从Enum对象类中获取.values()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为任何枚举对象创建通用方法,该方法将检查枚举是否具有指定的值名称,但是作为 Enum 类型的对象,我无法使用方法 values(); 。为什么?

I want to create universal method, for any enum object, that will check if enum has specified value name, but as Enum type object I am unnable to use method values();. Why?

有什么方法可以从 Enum 类型的对象中获取值?

Is there any way to get values from an Enum type object?

我需要这样的方法来检查配置中的值是否为 myEnum.valueOf(String); ,因为如果给定的字符串错误,那么它将引发异常(我不希望这样)。

I need method like this to check if value from configuration is a valid string for myEnum.valueOf(String); because if given string will be wrong then it will throw an exception (and I do not want it).

我希望我的方法看起来像这样:

I want my method to look like this:

public static Boolean enumContains(Enum en, String valueString){
    return toStringList(en.values()).contains(valueString.toUpperCase());
}

但是没有方法 Enum.values() 。如何正确创建此方法?

But there is no method Enum.values(). How to create this method correctly?

推荐答案

Enum#values 是由编译器生成的方法,因此除非您传入特定的枚举而不是 Enum<?> 。否则,不能在编译时使用它。

Enum#values is a method that is generated by the compiler, so you cannot use it at compile time unless you pass in a specific enum and not Enum<?>.

请参阅: https://stackoverflow.com/a/13659231/7294647

一种解决方案是传入 Class< E扩展Enum< E>> 并使用 Class#getEnumConstants

One solution would be to pass in a Class<E extends Enum<E>> instead and use Class#getEnumConstants:

public static <E extends Enum<E>> Boolean enumContains(Class<E> clazz, String valueString){
    return toStringList(clazz.getEnumConstants()).contains(valueString.toUpperCase());
}

如果您有一个名为 MyEnum ,那么您只需将 MyEnum.class 传递为第一个参数。

If you have an enum named MyEnum, then you can simply pass in MyEnum.class as the first argument.

这篇关于为什么我不能从Enum对象类中获取.values()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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