Java 使用反射从接口获取注释
我有下一个界面:Java 使用反射从接口获取注释,java,reflection,annotations,Java,Reflection,Annotations,我有下一个界面: public interface AG { @Params(param = {"user","userN"}) public String addUse(){} } 现在,我想得到反射中的注释,所以我写了下一个: Method[] methods = AG.class.getDeclaredMethods(); for (int i = 0; i<methods.length; i++){ String name = me
public interface AG {
@Params(param = {"user","userN"})
public String addUse(){}
}
现在,我想得到反射中的注释,所以我写了下一个:
Method[] methods = AG.class.getDeclaredMethods();
for (int i = 0; i<methods.length; i++){
String name = methods[i].getName();
if (name.equals("addUse")){
Method method = methods[i];
Annotation[] annotaions = method.getAnnotations();}}
Method[]methods=AG.class.getDeclaredMethods();
对于(int i=0;i您的代码将仅适用于有权在运行时进行内省的注释。特别是,它应该是运行时
,如下所示:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Params {
...
顾名思义,使用相应的字节码确定有关注释的信息保留到什么时候:
- (不为注释生成字节码)
- (生成对注释类型的
RuntimeInvisibleAnotations
引用)
- (生成对注释类型的
RuntimeVisiableAnnotations
引用)
请注意,这意味着,理论上,VM可以提供类保留注释。但实际上,情况并非如此(在Oracle JVM上肯定不是这样)