从没有isAnnotationPresent的字段检查注释

时间:2015-01-09 17:18:24

标签: java reflection annotations

我需要检查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是否有注释?

1 个答案:

答案 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();
        }
    }
}
相关问题