注释不可见?

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();
        }
    }
}

答案 1

您必须为注释定义@Retention

@Retention(RetentionPolicy.RUNTIME)
public @interface Marker {}

否则,注释不会在运行时保留。

(如果要限制注释仅在类上的使用,也可以添加显式)@Target(ElementType.TYPE)

作为旁注 - 将注释定义为内部类不是一种常见的做法。


答案 2

默认情况下,批注保留策略为 ,这不会使您的批注可用于反射。在声明批注时,应限定它。CLASS