个人资料
注释在Java 1.5中引入,提供代码的其他信息。 现在被广泛使用。 除了内置于Java中的注释外,还可以自定义注释。 自定义注释的示例如下所示。
@target(elementtype.type ) )。
@ retention (retention policy.runtime ) )。
@Inherited
@Documented
公共@接口msg {
String DEFAULT_MSG='msg ';
字符串msg (default default _ msg
}
自定义注释分析:
1.@interface关键字定义注释,
2 .评论可以用其他评论修饰。 说是评论,这也太绕远了。 最重要的是元评论。
3 .评论与界面类似,可以在内部定义常量和方法。
4 .评论定义的方法有一些限制。 方法不能有参数; 返回值只能是基本类型、字符串、类、枚举、注释和上述类型的数组。 可以包含默认值。
二元评论
元注释是定义四种类型注释的注释: @Target、@Retention、@Inherited和@Documented。
2.1 @Target
说明注释的使用目的。 值如下。
ElementType.PACKAGE注释会影响包
ElementType.TYPE注释影响类型(类、接口、注释和枚举)
ElementType.ANNOTATION_TYPE注释会影响注释
ElementType.CONSTRUCTOR注释影响构建方法
ElementType.METHOD注释会影响方法
ElementType.PARAMETER注释会影响方法参数
ElementType.FIELD注释会影响属性
ElementType.LOCAL_VARIABLE注释会影响局部变量
默认值适用于上述任一目标。
@Target注释的源代码如下:
@Documented
@ retention (retention policy.runtime ) )。
@ target (element type.annotation _ type ) )。
公共@接口目标{
元素类型[ ] value (;
}
注释返回值为ElementType[]、ElementType枚举类型,枚举值是@Target注释的理想值。 方法名称value。 允许在使用注释时不指定方法名称。
2.2 @Retention
说明评论的生命周期。 值如下。
RetentionPolicy.SOURCE源代码保留,可以在编译时处理
保存在RetentionPolicy.CLASS Class文件中,可以在加载Class时处理
RetentionPolicy.RUNTIME运行时暂挂,可运行时处理
缺省RetentionPolicy.CLASS值
@Retention注释源如下:
@Documented
@ retention (retention policy.runtime ) )。
@ target (element type.annotation _ type ) )。
公共@接口保留{
保留策略值(;
}
注释的返回值是枚举类型的RetentionPolicy,枚举值是@Retention注释的理想值。
2.3 @已隐藏
如果用@Inherited限定的注释作用于类,则标记该注释用于该类的子类。
@Inherited注释的源代码如下:
@Documented
@ retention (retention policy.runtime ) )。
@ target (element type.annotation _ type ) )。
公共@ interface inherited {
}
2.4 @文档
注释可以记录下来,是标注的注释。
生成javadoc时,不包含注释,但如果注释由@Documented限定,则生成的文档将包含注释。
@Documented注释的源代码如下:
@Documented
@ retention (retention policy.runtime ) )。
@ target (element type.annotation _ type ) )。
公共@接口文档{
}
3自定义注释示例
3.1自定义注释
@target(elementtype.type ) )。
@ retention (retention policy.runtime ) )。
@Inherited
@Documented
公共@接口msg {
String DEFAULT_MSG='msg ';
字符串msg (default default _ msg;
}
3.2使用自定义注释
@msg(msg='test ' ) ) )。
公共类测试{
}
3.3获取评论
公共类主{
publicstaticvoidmain (字符串[ ] args ) {
测试测试=new test (;
Class tClass=test.getClass (;
msgmsg=(msg ) tclass.getannotation ) msg.class;
system.out.println(msg.msg );
}
}
执行结果: Test
因为Msg注释的生命周期为RetentionPolicy.RUNTIME,所以运行时可以通过反射获取。 编译器处理的注释可以使用APT处理。