获得带注释的字段变量额外信息
问题描述:
我有一个具有某些属性的类,它们使用一个自定义注释进行注释,并且我希望将其信息放入另一个类中。获得带注释的字段变量额外信息
如何创建检索注释实例以及如何获取其额外信息?
我的源代码:
/**custom annotation **/
public @interface Info {
public String name();
}
/**class where i used custom annotation **/
class ABC {
@Info(name="Institution Name")
private String Name;
}
答
您需要与保留策略RetentionPolicy.RUNTIME
您的注释,以便能够acceed到运行时的注释。
@Retention(RetentionPolicy.RUNTIME)
public @interface Info {
public String name();
}
之后,你有为了让您的field.You可以getAnnotation(Info.class)
方法让你的注释使用this.getClass().getDeclaredField("name")
。您将得到您的注释实例,并且您将能够加入其信息。
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-
的可能的复制[在运行时获取的注释信息(http://stackoverflow.com/questions/4435036/get-the-annotation-information-at-runtime) – Aaron