注释不可见?
2022-09-01 20:26:31
这让我感到困惑。我有一个带有自定义注释的类,但我似乎无法验证注释是否存在。我在这里做错了什么?如果我运行(见下文),我得到这个结果:MyOperationTest
implements Library.Operation: true
has @Library.Marker: false
Tada!
图书馆.java:
package com.example.gotchas;
public class Library {
private Library() {}
public @interface Marker {}
public interface Operation {
public void execute();
}
}
我的操作.java:
package com.example.gotchas;
@Library.Marker
public class MyOperation implements Library.Operation {
@Override public void execute() {
System.out.println("Tada!");
}
}
我的操作测试.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();
}
}
}