java子类的定义,如何强制一个Java子类来定义一个注释?

If a class defined an annotation, is it somehow possible to force its subclass to define the same annotation?

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:

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 {}

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.

解决方案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值