如何强制一个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
注释,preventing一个的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,在编译时。
参见:<一href=\"http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api\" rel=\"nofollow\">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
这篇关于如何强制一个Java子类来定义一个注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!