首页 > 编程知识 正文

java注解的实现原理,java注解获取被注解的字段

时间:2023-05-06 10:27:46 阅读:177787 作者:3030

Repeatable使用场景:如果需要多次使用相同的注释,则必须使用@Repeatable。

实例:生活中一个人往往有多重身份。 如果我把各自的身份作为一个注释该怎么用呢? 什么? 什么?

首先,声明Persons类以包含所有id

@target(elementtype.type ) retention ) retentionpolicy.runtime ) public @ interface persons { person [ ] value; }其中@Target是声明人员注释的范围,参数ElementType.Type表示可以对类、接口、枚举和注释等类型进行注释。

@Retention是注释的有效时间,RetentionPolicy.RUNTIME是程序运行时的时间。

佩尔森评论:

@repeatable(persons.class ) public@interfaceperson ) stringrole ) ) default '; } @Repeatable括号中的对应于用于存储注释内容的容器。

声明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 ) ); }以下代码输出相同的结果,但可以先判断是否是对应的注释,非常严密。

if (man.class.isannotationpresent (persons.class ) ) personsp2=man.class.get annotation (persons.class ); 个人: p2.value () (system.out.println ) t.role ) ); }运行结果:

1

首席执行官

husband

教父

son

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。