[英]get annotated field variable extra info
I have a class which has some properties and they are annotated with one custom annotation, and I want its information in another class. 我有一个具有一些属性的类,并且使用一个自定义注释对其进行注释,并且我希望将其信息包含在另一个类中。
How to create retrieve the annotation instance and how to get its extra info? 如何创建检索注释实例以及如何获取其额外信息?
My source code: 我的源代码:
/**custom annotation **/
public @interface Info {
public String name();
}
/**class where i used custom annotation **/
class ABC {
@Info(name="Institution Name")
private String Name;
}
You need to make your annotation with retention policy RetentionPolicy.RUNTIME
in order to be able to acceed to your annotation on RUNTIME. 您需要使用保留策略
RetentionPolicy.RUNTIME
进行注释,以便能够在RUNTIME上使用注释。
@Retention(RetentionPolicy.RUNTIME)
public @interface Info {
public String name();
}
After that you have to use this.getClass().getDeclaredField("name")
in order to get your field.You can get your annotation with getAnnotation(Info.class)
method. 之后,您必须使用
this.getClass().getDeclaredField("name")
才能获取this.getClass().getDeclaredField("name")
您可以使用getAnnotation(Info.class)
方法获取注释。 You will get an instance of your annotation and you will be able to acceed to its information. 您将获得注释的实例,并且能够访问其信息。
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredField-java.lang.String- https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getAnnotation-java.lang.Class- https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredField-java.lang.String- https://docs.oracle.com/javase/8/docs/ api / java / lang / Class.html#getAnnotation-java.lang.Class-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.