内部源保留注释的表示

Representation of inner source-retained annotation

我们有这个 class:

public class MyClass {
    @Retention(RetentionPolicy.SOURCE)
    private @interface MyInterface { }

    @MyInterface
    public void hello() { }
}

如您所见,它有一个内部的、仅限源代码的注释。我的问题是:导出的二进制文件 (jar) 是否应该包含 MyClass$MyInterface.class 文件?如果我们看保留,我们可以说不是,因为这个注释应该被编译器丢弃。然而,它仍然被添加到 MyClass.class 中的内部 classes 列表中,并且 MyClass$MyInterface.class 文件也被创建。

当我们 运行 一个注释处理器反对这个 class

public class MyProcessedClass extends MyClass {}

如果我们call

注释处理失败
myClass.getEnclosedElements()

MyClass$MyInterface.class 不存在。如果存在 MyClass$MyInterface.class,则处理正常。

(original problem)

My question is: should the exported binary (jar) contain the MyClass$MyInterface.class file or not?

应该。

13.1. The Form of a Binary:

  1. Every class must contain symbolic references to all of its member types, and to all local and anonymous classes that appear in its methods, constructors, static initializers, instance initializers, and field initializers.

4.7.6. The InnerClasses Attribute:

If a class or interface has members that are classes or interfaces, its constant_pool table (and hence its InnerClasses attribute) must refer to each such member, even if that member is not otherwise mentioned by the class.

所以 MyClass 必须引用 MyInterface。虽然我没有对此的引用,但似乎如果有对特定 class 的引用,那么应该编译 class。