[英]Java enum.valueOf(String) and enum.class
I have few enums like the following: 我有几个如下的枚举:
public enum Season {
SPRING, SUMMER, AUTUM, WINTER
}
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
I am trying to write a common method for a concern. 我正在尝试为关注的问题写一个通用方法。
private void doSomethingWithAnyEnum(Class enumClass,String checkThisProperty)
{
if(EnumUtils.isValidEnum(enumClass, checkThisProperty))
{
//here i should be able to call valueOf(String) method on enum
//without bothering about the type coming in.
}
}
So that I can call this method like: 这样我就可以像这样调用此方法:
doSomethingWithAnyEnum(Days.class,"blah") ;
doSomethingWithAnyEnum(Seasons.class,"blah");
I am stuck on how to pass a enum and use it's class and name in the method using the same thing. 我被困在如何传递枚举并使用同一件事在方法中使用它的类和名称的问题上。 I tried using simpleName()
but it doesn't do the job here. 我尝试使用simpleName()
但在这里不起作用。 Is there a way to do this? 有没有办法做到这一点?
You may want to modify your function like this: 您可能要像这样修改函数:
public <T extends Enum<T>> void doSomethingWithAnyEnum(Class<T> tClass, String name) {
T t = Enum.valueOf(tClass, name);
}
Your original method took a random Class enumClass
class type, which accept any class. 您的原始方法采用了随机的Class enumClass
类类型,该类型可以接受任何类。 It will throw runtime exceptions when treat input class as enum 将输入类视为枚举时,它将抛出运行时异常
EnumUtils
from Apache Commons already has a method to do this: getEnum
. 来自Apache Commons的EnumUtils
已经有一种方法可以做到这一点: getEnum
。 As you're already using it for isValidEnum
, it makes sense to use it for this as well. 由于您已经将它用于isValidEnum
,因此也可以将其用于此。
Your method signature should also use generics rather than raw types to enforce at compile-time that doSomethingWithAnyEnum
is called with an enum and not any old class. 您的方法签名还应该使用泛型而不是原始类型来在编译时强制执行,即使用枚举而不是任何旧类调用doSomethingWithAnyEnum
。 I have fixed that for you as well. 我也为您修复了该问题。
private <E extends Enum<E>> void doSomethingWithAnyEnum(Class<E> enumClass,
String checkThisProperty)
{
if (EnumUtils.isValidEnum(enumClass, checkThisProperty))
{
final E value = EnumUtils.getEnum(enumClass, checkThisProperty);
System.out.println(value.name()); //or whatever else you want to do
}
}
Without this change to the method signature, I could call this method with 如果没有方法签名的更改,我可以使用
doSomethingWithAnyEnum(String.class, "hello")
and it would only fail at runtime. 而且只会在运行时失败。 It's better to do the check at compile-time. 最好在编译时进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.