needermen
needermen

Reputation: 43

Can't access annotation of field in Java

I have annotation

public @interface Equals {
String name() default "unknown";
}

and class whose field is annotated by Equals

public class TransportSearch {
@Equals(name="vin")
public String vin = null;
}

and I have one method in another class

public String (TransportSearch transportSearch){
    Field[] fields = transportSearch.getClass().getDeclaredFields();

    String vin = null;

    for(Field field : fields){
        try {
            Equals annot = field.getAnnotation(Equals.class);

            if(annot!=null && annot.name().equals("vin")){
                try {
                    vin = (String) field.get(transportSearch);
                } catch (IllegalAccessException e){
                    e.printStackTrace();
                }
            }

        } catch(NullPointerException e) {
            e.printStackTrace();
        }
    }
    return vin;
}

unfortunately in this method field.getAnnotation(Equals.class) returns null and I can't understand why? Can you help me?

Upvotes: 2

Views: 2340

Answers (2)

LLPF
LLPF

Reputation: 1

If you use kotlin:

class TransportSearch {
  @field:Equals(name = "vin")
  var vin:String? = null
}

Upvotes: -1

Balder
Balder

Reputation: 8708

You must set the RetentionPolicy of your annotation to RetentionPolicy.RUNTIME:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Equals {
    String name() default "unknown";
}

The default RetentionPolicy is RetentionPolicy.CLASS, which means the annotation does not need to be available at runtime.

Upvotes: 5

Related Questions