您的位置 首页 技术

java基础之注解

1、元注解 1.1 @Target 【作用】 用于指定所标注的注解可以使用的位置,例如:@Target(ElementType.METHOD):表示可以使用在方法上,其他结构不能使…

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 "我是一个注解";}

输出结果:

baae4b0f6dd70e1ee873cd7c5c5af4a.png

相关文章教程推荐:java入门学习

以上就是java基础之注解的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/12124.html

为您推荐

返回顶部