我们有这样的类(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?
应该。
- 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 itsInnerClasses
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/