这让我很困惑。我有一个带有自定义注释的类,我似乎无法验证注释是否存在。我在这做错了什么?如果我运行MyOperationTest
(见下文),我会得到这个结果:
implements Library.Operation: true
has @Library.Marker: false
Tada!
Library.java:
package com.example.gotchas;
public class Library {
private Library() {}
public @interface Marker {}
public interface Operation {
public void execute();
}
}
MyOperation.java:
package com.example.gotchas;
@Library.Marker
public class MyOperation implements Library.Operation {
@Override public void execute() {
System.out.println("Tada!");
}
}
MyOperationTest.java:
package com.example.gotchas;
public class MyOperationTest {
static public void main(String[] args)
{
try {
Class<?> cl = Class.forName("com.example.gotchas.MyOperation");
boolean implementsLibraryOperation =
Library.Operation.class.isAssignableFrom(cl);
boolean hasLibraryMarker =
cl.isAnnotationPresent(Library.Marker.class);
System.out.println("implements Library.Operation: "
+implementsLibraryOperation);
System.out.println("has @Library.Marker: "+hasLibraryMarker);
if (implementsLibraryOperation)
{
Class<? extends Library.Operation> opClass =
cl.asSubclass(Library.Operation.class);
Library.Operation op = opClass.newInstance();
op.execute();
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:30)
您必须为注释定义@Retention
:
@Retention(RetentionPolicy.RUNTIME)
public @interface Marker {}
否则注释不会在运行时保留。
(如果您只想在类上限制注释的使用,也可以添加显式@Target(ElementType.TYPE)
)
作为旁注 - 将注释定义为内部类并不常见。
答案 1 :(得分:2)
默认情况下,注释保留策略为CLASS
,不会使您的注释可用于反射。在声明注释时,您应该对其进行限定。