我正在尝试使用反射来发现使用@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()
给出了相同的结果
答案 0 :(得分:2)
查看@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