如果一个类定义了一个注释,是否有可能迫使其子类定义相同的注释?
例如,我们有一个简单的类/子类对,它们共享@Author @interface.
我想做的事情,就是迫使每个进一步的子类定义相同的@Author注释,以防止RuntimeException将来出现问题。
TestClass.java:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface Author { String name(); }
@Author( name = "foo" )
public abstract class TestClass
{
public static String getInfo( Class extends TestClass> c )
{
return c.getAnnotation( Author.class ).name();
}
public static void main( String[] args )
{
System.out.println( "The test class was written by "
+ getInfo( TestClass.class ) );
System.out.println( "The test subclass was written by "
+ getInfo( TestSubClass.class ) );
}
}
TestSubClass.java:
@Author( name = "bar" )
public abstract class TestSubClass extends TestClass {}
我知道我可以在运行时枚举所有批注并检查是否丢失了@Author,但是我真的很想在编译时执行此操作(如果可能)。