java - 内部源保留注释的表示

标签 java annotations annotation-processing

我们有这样的类(class):

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

    @MyInterface
    public void hello() { }
}

如您所见,它有一个内部的、仅限源的注释。我的问题是:导出的二进制文件(jar)是否应该包含 MyClass$MyInterface.class 文件?如果我们查看保留情况,我们可以说不是,因为这个注释应该被编译器丢弃。不过,它仍然会添加到 MyClass.class 中的内部类列表中,并且还会创建 MyClass$MyInterface.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。尽管我没有对此的引用,但似乎如果存在对特定类的引用,则应该编译该类。

关于java - 内部源保留注释的表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30531136/

相关文章:

asp.net-mvc - 在 Controller 级别应用时如何禁用操作属性?

android - Dagger 不会为 TestModule 生成适配器

Java 11 模块信息 : how to register an annotation processor

kotlin - 在 Kotlin 注释处理期间如何访问方法体?

java - 尝试使用 AnchorPane 的扩展版本时出现实例化和加载异常

java - 如何增加音频文件的音量

java - 在 acceleo 中使用注释的问题

java - class.getAnnotation 和 getAnnotations 不能正常工作

java - 将序列化对象写入文件

java - 从自定义标签返回值到jsp