如何强制 Java 子类定义注释? [英] How do I force a Java subclass to define an Annotation?
问题描述
如果一个类定义了一个注解,是否可以强制其子类定义相同的注解?
If a class defined an annotation, is it somehow possible to force its subclass to define the same annotation?
例如,我们有一个简单的类/子类对,它们共享 @Author @interface.
我想要做的是强制每个进一步的子类定义相同的 @Author
注释,防止 RuntimeException
在路上的某个地方.
For instance, we have a simple class/subclass pair that share the @Author @interface.
What I'd like to do is force each further subclass to define the same @Author
annotation, preventing a RuntimeException
somewhere down the road.
TestClass.java:
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:
TestSubClass.java:
@Author( name = "bar" )
public abstract class TestSubClass extends TestClass {}
我知道我可以在运行时枚举所有注释并检查缺少的 @Author
,但如果可能的话,我真的很想在编译时这样做.
I know I can enumerate all annotations at runtime and check for the missing @Author
, but I'd really like to do this at compile time, if possible.
推荐答案
您可以在编译时使用 JSR 269 做到这一点.请参阅:http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api
You can do that with JSR 269, at compile time. See : 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
Edit 2020-09-20: Link is dead, archived version here : https://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html
这篇关于如何强制 Java 子类定义注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!