Kleber Mota
Kleber Mota

Reputation: 9055

Get the name of an annotated field

If I had defined an annotation like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Input {

    String type() default "text";
    String name();
    String pattern() default "";

}

and use it for this methods:

@Column(name="nome", unique = true, nullable = false)
@Order(value=1)
@Input
private String nome;

@Column(name="resumo", length=140)
@Order(value=2)
@Input
private String resumo;

Is there any way to assign to attribute name the name of the annotated field (for instance: for the field String nome the value would be nome and for the field String resumo would be resumo)?

Upvotes: 6

Views: 10668

Answers (1)

Jp Vinjamoori
Jp Vinjamoori

Reputation: 1271

You cannot default the annotation variables to field names. But where ever you are processing the annotation, you can code such that it defaults to field's name. Example below

Field field = ... // get fields
Annotation annotation = field.getAnnotation(Input.class);

if(annotation instanceof Input){
    Input inputAnnotation = (Input) annotation;
    String name = inputAnnotation.name();
    if(name == null) { // if the name not defined, default it to field name
        name = field.getName();
    }
    System.out.println("name: " + name); //use the name
}

Upvotes: 6

Related Questions