Kleber Mota
Kleber Mota

Reputation: 9055

Read property of an annotation in another

If I declare an attribute from my class this way:

@Order(value=1)
@Input(name="login")
private String login;

and the definition for @Input is this:

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

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

    String tag() default "<custom:Input ordem=''/>";

}

Is there any way to read the property value from @Order and use for the property tag from @Input?

Upvotes: 1

Views: 1659

Answers (2)

Holger
Holger

Reputation: 298103

Just consider the good old compile-time constants:

static final int MEANINGFUL_NAME = 1;

@Order(value=MEANINGFUL_NAME)
@Input(name="login", tag="<custom:Input order='"+MEANINGFUL_NAME+"'>")
private String login;

The rules for compile time constants still apply when providing values to annotations, so you can calculate constants using other constants and you may place the constants in other classes and use static imports. They may even get placed into the annotation just like into other interfaces which may come handy when they are some kind of standard values for the annotation.

@interface Example {
  int COLD = -1, WARM = 0, HOT = 1;
  int value() default WARM;
}

@Example(Example.HOT)

or

import static stackoverflow.Example.*;
// …
@Example(HOT)

Upvotes: 1

Kumar Abhinav
Kumar Abhinav

Reputation: 6665

One of the ways of reading metadata such as annotations,fields and classes is Reflection.You can use reflection to read meta -data of an annotation too.

This will work only if @Order annotation has RuntimePolicy of Runtime @Retention(RetentionPolicy.RUNTIME)

Note :- Annotations also are Class objects.Each annotation is a special type of interface and interfaces are also treated as java.lang.Class Objects.

Field loginVariaable = .../// get your login attribute from your Class Object using reflection 
Order order = loginVariaable.getAnnotation(Order.class)
int orderValue = order.value();

Input inputObject = loginVariaable.getAnnotation(Input.class)
String inputName= inputObject.name();

Generics helps you in getting the Annotation object without casting to Annotation Object.Also ,note that all annotations implicitly extends java.lang.annotation.Annotation

Upvotes: 1

Related Questions