没有未经检查的警告的通用枚举解析器
Generic Enum Parser without unchecked warning
如何去掉下面代码中的@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 );
}
所有 Enum<E>
sub类 都有一个 return 其 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);
}
编辑:您之前的解决方案是错误的,不仅仅是风格不佳。
public final Class<E> getDeclaringClass()
Returns the Class object corresponding to this enum constant's enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (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.)
如果传入的 Class
是 "enum constants with constant-specific class bodies" 的 Class
,Enum.valueOf(Class, String)
可能会抱怨。 Class.isEnum()
return false
类.
如何去掉下面代码中的@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 );
}
所有 Enum<E>
sub类 都有一个 return 其 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);
}
编辑:您之前的解决方案是错误的,不仅仅是风格不佳。
如果传入的public final Class<E> getDeclaringClass()
Returns the Class object corresponding to this enum constant's enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (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.)
Class
是 "enum constants with constant-specific class bodies" 的 Class
,Enum.valueOf(Class, String)
可能会抱怨。 Class.isEnum()
return false
类.