首页 > 编程知识 正文

元注解的作用,java序列化

时间:2023-05-04 17:59:33 阅读:147829 作者:1361

1 .首先看来源文件

//*

* indicatesthatanannotationtypeisautomaticallyinherited.if

* aninheritedmeta-annotationispresentonanannotationtype

* declaration,andtheuserqueriestheannotationtypeonaclass

* declaration,andtheclassdeclarationhasnoannotationforthistype,

* then the class ' ssuperclasswillautomaticallybequeriedforthe

* annotation type.thisprocesswillberepeateduntilanannotationforthis

* type is found,orthetopoftheclasshierarchy (object ) )。

* is reached.ifnosuperclasshasanannotationforthistype,then

* thequerywillindicatethattheclassinquestionhasnosuchannotation。

*

*

notethatthismeta-annotationtypehasnoeffectiftheannotated

* typeisusedtoannotateanythingotherthanaclass.note also

* thatthismeta-annotationonlycausesannotationstobeinherited

*来自super classes; annotationsonimplementedinterfaceshaveno

*效率。

*

* @author Joshua Bloch

* @since 1.5

* @jls 9.6.3.3 @Inherited

*/

@Documented

@ retention (retention policy.runtime ) )。

@ target (element type.annotation _ type ) )。

公共@ interface inherited {

}

上述代码注释部分是谷歌翻译大法,大致意思是

指示注释类型将自动继承。 如果注释类型声明中存在继承的元注释,并且用户在类声明中查询注释类型,而类声明中没有该类型的注释,则该类的超类将自动查询注释类型。 重复此过程,直到找到此类型的注释或到达类层次(Object )的顶部。 如果超类没有此类型的注释,则查询将指示目标类没有此类注释。

请注意,使用注释类型对类以外的内容进行注释时,此元注释类型不起作用。 请注意,此元注释只是从超类继承注释; 实现的接口注释无效。

根据上面的描述,可以看到使用此注释的注释父类的子类可以继承父类的注释。

2 .代码测试

2.1 @有inherited评论

@target(elementtype.type ) )。

@ retention (retention policy.runtime ) )。

@Inherited

公共@ interface inherited test {

字符串值(;

}

@ inherited test (拥有“inherited”) )。

公共类人员{

公共语音方法

}

公共语音方法2 () {

}

}

publicclassstudentextendsperson {

}

测试:

公共类测试嵌入{

publicstaticvoidmain (string [ ] args ) {

classstudentclass=student.class;

student class.isannotationpresent (inherited test.class ) ) }

system.out.println (student class.get annotation (inherited test.class ).value ();

}

}

}

输出:

2.2 @无inherited评论

@target(elementtype.type ) )。

@ retention (retention policy.runtime ) )。

公共@ interfaceisnotinherited {

字符串值(;

}

@ is not inherited (不拥有“inherited”) )

公共类人员{

公共语音方法

}

公共语音方法2 () {

}

}

publicclassstudentextendsperson {

}

测试:

公共类测试嵌入{

publicstaticvoidmain (string [ ] args ) {

classstudentclass=student.class;

student class.isannotationpresent (is not inherited.class ) }

system.out.println (student class.get annotation (is not inherited.class ).value );

}

}

}

由于不输出任何内容,因此可以看出具有不带@Inherited注释的注释的类的子类不继承注释。

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