您好,欢迎访问一九零五行业门户网

java基础之注解

1、元注解
1.1 @target
【作用】
用于指定所标注的注解可以使用的位置,例如:@target(elementtype.method):表示可以使用在方法上,其他结构不能使用;@target({elementtype.method, elementtype.type}):表示可以使用在方法和接口、类、枚举上。
相关在线视频教程:java课程
1.2 @retention
【作用】
用于指定所标注的注解保留阶段,该注解共有三个值:
@retention(retentionpolicy.source):表示保留到源代码阶段,编译后消失
@retention(retentionpolicy.class):表示保留到编译阶段,运行后消失
@retention(retentionpolicy.runtime):表示保留到运行阶段,若要通过反射读取注解信息,需要指定该注解保留阶段为 runtime
1.3 @inherited
【作用】
表明这个注解是否可以被子类继承。
1.4 @documented
【作用】
表明这个注解是否可以被 javadoc 读取到文档中。
2、注解声明
【格式】
【元注解】
【修饰符】 @interface 注解名 { 注解体 }
【例子】
@target(elementtype.method)@retention(retentionpolicy.runtime)public @interface myannotation {}
3、配置参数声明
【格式】
【数据类型】 参数名() default 默认值;
default 默认值:在需要设置默认值时,可以添加,需要设置时,不用写;
数据类型只能是:基本数据类型、string、class、enum、annotation,及以上所有类型的一维数组。
如果参数成员只有一个或使用频率较高的参数可以定义参数名为:value,在使用注解时,若参数名为 value 可以省略,直接写输入的值。
【例子】
@target(elementtype.method)@retention(retentionpolicy.runtime)public @interface myannotation {string name() default "";}
4、读取注解信息
只有注解标注 @retention(retentionpolicy.runtime) 才能通过反射读取。
读取注解信息通过反射读取,具体如下:
import java.lang.annotation.elementtype;import java.lang.annotation.retention;import java.lang.annotation.retentionpolicy;import java.lang.annotation.target;public class testinterface { public static void main(string[] args) { myannotation myannotation = myclass.class.getannotation(myannotation.class); string value = myannotation.value(); system.out.println(value); }}@myannotationclass myclass {}@target(elementtype.type)@retention(retentionpolicy.runtime)@interface myannotation { string value() default "我是一个注解";}
输出结果:
相关文章教程推荐:java入门学习
以上就是java基础之注解的详细内容。
其它类似信息

推荐信息