如果一个类定义了一个注释,是否有可能强制其子类定义相同的注释?
例如,我们有一个简单的类/子类对,它们共享@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
,但我真的很想在编译时执行此操作,如果可能的话.