我需要检查Field
是否有注释,但我无法使用isAnnotationPresent
进行检查。
public void foo(Class<?> clazz) {
Field[] fieldReflection = clazz.getDeclaredFields();
for (Field fieldReflect : fieldReflection){
if (fieldReflect.isAnnotationPresent(FieldSize.class){
//do something
} else {
throw new Exception();
}
}
}
这就是我今天的做法,还有另一种方法来检查Field
是否有注释?
答案 0 :(得分:0)
我刚刚发现了怎么做..
除了使用isAnnotationPresent
之外,我还可以这样检查:
FieldSize annotation = fieldReflect.getAnnotation(FieldSize.class);
if (annotation != null) {
所以最终的代码就像:
public void foo(Class<?> clazz) {
Field[] fieldReflection = clazz.getDeclaredFields();
for (Field fieldReflect : fieldReflection){
FieldSize annotation = fieldReflect.getAnnotation(FieldSize.class);
if (annotation != null){
//do something
} else {
throw new Exception();
}
}
}