[英]Generic Enum Parser without unchecked warning
How to remove @SuppressWarnings("unchecked")
in the following code? 如何在以下代码中删除
@SuppressWarnings("unchecked")
?
public <T extends Enum<T>> T getEnum( String key, T dflt ) {
final String value = properties.getProperty( key, dflt.name());
@SuppressWarnings("unchecked")
final Class<T> clazz = (Class<T>)dflt.getClass();
return Enum.valueOf( clazz, value );
}
All Enum<E>
subclasses have a method that returns its Class
that is properly parameterized. 所有
Enum<E>
子类都有一个返回正确设置了参数的Class
的方法。
public <T extends Enum<T>> T getEnum(String key, T dflt) {
final String value = properties.getProperty(key, dflt.name());
final Class<T> clazz = dflt.getDeclaringClass();
return Enum.valueOf(clazz, value);
}
EDIT: Your previous solution is WRONG, not just bad style. 编辑: 您以前的解决方案是错误的,不仅是糟糕的风格。
public final Class<E> getDeclaringClass()
Returns the Class object corresponding to this enum constant's enum type.
返回与此枚举常量的枚举类型相对应的Class对象。 Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass().
当且仅当e1.getDeclaringClass()== e2.getDeclaringClass()时,两个枚举常量e1和e2属于相同的枚举类型。 (The value returned by this method may differ from the one returned by the Object.getClass() method for enum constants with constant-specific class bodies.)
(对于具有特定于常量的类主体的枚举常量,此方法返回的值可能不同于Object.getClass()方法返回的值。)
Enum.valueOf(Class, String)
may complain if the Class
passed in is the Class
for "enum constants with constant-specific class bodies". Enum.valueOf(Class, String)
可能会抱怨如果Class
传入是Class
为“以特定的恒定类主体枚举常数”。 Class.isEnum()
will return false
for those classes. 对于这些类,
Class.isEnum()
将返回false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.