2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.