**
Repeatable使用场景: **
如果需要重用某个注释,并且希望用同一注释表示所有形式,请使用@Repeatable注释。
**
实例*
生活中一个人往往有各种各样的身份,每一个身份都可以用注释来表示。
声明人员注释,以声明包括所有id
@target(elementtype.type ) retention ) retentionpolicy.runtime ) public @ interface persons { person [ ] value; }其中@Target注释声明Persons的有效范围,参数ElementType.Type表示可以对类、接口、枚举和注释等类型进行注释。
@Retention是注释的有效时间,RetentionPolicy.RUNTIME意味着注释将保留到程序运行时,并加载到JVM中,然后可以在程序运行时检索。
佩尔森评论
@repeatable(persons.class ) public@interfaceperson ) stringrole ) ) default '; } @Repeatable括号中的Persons.class相当于用于存储注释内容的容器。
创建Man类并将一些身份添加到Man类中。 另外,添加多个人物评论
@person(role='CEO ' ) person ) role='Husband ' ) person ) role='father ' ) person ) role='son ' ) publiccon }梅
publicstaticvoidmain (string [ ] args ) annotation [ ] annotations=man.class.get annotations ); system.out.println (annotations.length; 人员SP1=(人员) annotations[0]; 个人: P1.value () (system.out.println ) t.role ) ); }运行结果:
1
首席执行官
husband
教父
son