Lim*_*ver 11 java annotations subclass
如果一个类定义了一个注释,是否有可能强制其子类定义相同的注释?
例如,我们有一个简单的类/子类对,它们共享@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 ) );
}
}
Run Code Online (Sandbox Code Playgroud)
TestSubClass.java:
@Author( name = "bar" )
public abstract class TestSubClass extends TestClass {}
Run Code Online (Sandbox Code Playgroud)
我知道我可以在运行时枚举所有注释并检查缺失@Author
,但我真的很想在编译时执行此操作,如果可能的话.
您可以在编译时使用 JSR 269 来做到这一点。请参阅: http: //today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api
编辑2020-09-20:链接已死,存档版本在这里:https://web.archive.org/web/20150516080739/http ://today.java.net/pub/a/today/2006/06/29 /validate-java-ee-annotations-with-annotation-processors.html