How to get attributes of annotations in Java using reflection?

Viewed 81

I have several data classes in java of which I want to know - using reflection - which fields have a certain annotation with a certain attribute which is the following:

@Column(columnDefinition = "text") // Text with unbound length
private String comment;

I figured how to get the annotations of the field and whether it is of type Column:

private boolean isStringFieldWithBoundLength(Field attr) {
    Annotation[] annotations = attr.getDeclaredAnnotations();
    for (Annotation ann : annotations) {
        Class<? extends Annotation> aClass = ann.annotationType();
        if (Column.class == aClass) {
            
            // ...
            
        }
    }
}

Now in the debugger I can see that the aClass object has the information about the provided parameters. Unfortunately I don't know how to access it with code. Is it possible to access this information in java?

1 Answers

You should be able to get the instance of that annotation (including your values) using

Column fieldAnnotation = attr.getAnnotation(Column.class);

If the field is not annotated with @Column, getAnnotation returns null. That means you don't need to iterate over attr.getDeclaredAnnotations();

You can then call fieldAnnotation.columnDefinition() or whatever custom field that your annotation might have.

Addition: your annotation needs to have @Retention(RetentionPolicy.RUNTIME) for that to work, otherwise your annotations will be removed from classes/fields/methods during compilation.

Related