简体   繁体   English

无法访问Java中的字段注释

[英]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 和其字段由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? 不幸的是,在此方法中, field.getAnnotation(Equals.class)返回null,我不明白为什么? Can you help me? 你能帮助我吗?

You must set the RetentionPolicy of your annotation to RetentionPolicy.RUNTIME : 您必须将注释的RetentionPolicy设置为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. 默认的RetentionPolicyRetentionPolicy.CLASS ,这意味着注释在运行时不需要可用。

If you use kotlin: 如果您使用kotlin:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM