João Rocha
João Rocha

Reputation: 135

Check an annotation from a Field without isAnnotationPresent

I need to check if there is an annotation present at a Field, but I can't use isAnnotationPresent to check it.

public void foo(Class<?> clazz) {
    Field[] fieldReflection = clazz.getDeclaredFields();

    for (Field fieldReflect : fieldReflection){
        if (fieldReflect.isAnnotationPresent(FieldSize.class){
            //do something
        } else {
            throw new Exception();
        }
    }
}

This is how I'm doing today, there is another way to check if the Field have an annotation?

Upvotes: 0

Views: 660

Answers (1)

Jo&#227;o Rocha
Jo&#227;o Rocha

Reputation: 135

I just found how to do..

Besides use isAnnotationPresent, I could check this way:

FieldSize annotation = fieldReflect.getAnnotation(FieldSize.class);
if (annotation != null) {

So the final code would be like:

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();
        }
    }
}

Upvotes: 1

Related Questions