使用反射获取java注释
我试图使用反射来发现用@Override注释(或任何注释)注释的“init”方法,但好的,这是我的示例,当然是简化了很多 基类:
public abstract class A
{
public void init()
{
}
}
下面是子类:
public class B extends A
{
String bla;
@Override
public void init()
{
}
public void init(String bla)
{
this.bla=bla;
}
}
因此,我运行以获取带注释的方法的代码如下:
public static void main(String[] args)
{
ClassLoader c = Main.class.getClassLoader();
try
{
Class<?> clazz = c.loadClass("correct.path.to.class.B");
for (Method method : clazz.getDeclaredMethods())
{
if (method.getName().equals("init"))
{
System.out.println(method.getDeclaredAnnotations().length);
}
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
这两种方法都找到了,但令人惊讶的是,在读取包含注释的数组长度时,我得到了两次“0”,知道这里有什么问题吗?
方法getAnnotation()
给出了相同的结果
# 1 楼答案
检查文档中的
@Override
和RetentionPolicy
。基本上,@Override
注释在运行时不可用,它是一个仅源代码的注释http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html
http://docs.oracle.com/javase/7/docs/api/java/lang/Override.html