Search code examples
javareflectionannotations

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?


Solution

  • 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.