我认为不可能删除编译器警告
最好的情况是像@tangens 那样将所有错误减少为一个。
发现两个论坛主题显示不成功的答案,并解释了更多的原因。
因此,我整理了一个完整的示例来演示我所看到的问题。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.List;
public class Test {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Detail {
String example();
}
public enum ExampleEnum {
FOO_BAR, HELLO_WORLD
}
@Detail(example = "FOO_BAR")
public ExampleEnum test;
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
populate(new Test());
}
public static void populate(Object o) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
final Field field = o.getClass().getField("test");
final Detail detail = field.getAnnotation(Detail.class);
System.out.println("Annotation = " + detail);
final String example = detail.example();
final Class<?> type = field.getType();
System.out.println("Field Class = " + type.getName());
if (List.class.isAssignableFrom(type)) {
} else if (Enum.class.isAssignableFrom(type)) {
Class<? extends Enum> enumType = type.asSubclass(Enum.class); // Enum is a raw type. References to generic type Enum<E> should be parameterized
Enum val = Enum.valueOf(enumType, example); // 1) Enum is a raw type. References to generic type Enum<E> should be parameterized
// 2) Type safety: Unchecked invocation valueOf(Class<capture#7-of ? extends Enum>, String) of the generic
// method valueOf(Class<T>, String) of type Enum
field.set(o, val);
}
}
}