Java自定义注解

Java自定义注解

注解是一种特殊的标记,可以用在方法、类、参数和包上,程序在编译或运行时可以检测到这些标记而进行一些特殊的处理。

  1. 注解的元素类型

    元注解主要有@Target,@Retention,@Documented,@Inherited,是用来解释注解的注解。

  2. @Target表示可以应用的java元素类型

Target类型描述
ElementType.TYPE应用于类、接口(包括注解类型)、枚举
ElementType.FIELD应用于属性(包括枚举中的常量)
ElementType.METHOD应用于方法
ElementType.PARAMETER应用于方法的形参
ElementType.CONSTRUCTOR应用于构造函数
ElementType.LOCAL_VARIABLE应用于局部变量
ElementType.ANNOTATION_TYPE应用于注解类型
ElementType.PACKAGE应用于包
ElementType.TYPE_PARAMETER1.8版本新增,应用于类型变量)
ElementType.TYPE_USE1.8版本新增,应用于任何使用类型的语句中(例如声明语句、泛型和强制转换语句中的类型)
  1. @Retention表明注解的生命周期
生命周期类型描述
RetentionPolicy.SOURCE编译时被丢弃,不包含在类文件中
RetentionPolicy.CLASSJVM加载时被丢弃,包含在类文件中,默认值
RetentionPolicy.RUNTIME由JVM 加载,包含在类文件中,在运行时可以被获取到
  1. @Documented表明该注解标记的元素可以被Javadoc或类似的工具文档化

  2. @Inherited表名该注解标记的类的子类也拥有这个注解

  3. 实例

(1)定义注解@MetaAnnotation

package com.reflection;

public @interface MetaAnnotation {
    String value();
}

(2)定义注解@MyAnnotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface MyAnnotation {
    String color() default "blue";
    //特殊的类型,如果只需要给value赋值,value变量可以省略
    String value();
    int[] arrayAttr() default {3, 4};
    //在注解中使用注解
    MetaAnnotation annotation() default @MetaAnnotation("abcd");
}

(3)注解测试类

package com.reflection;

@MyAnnotation(color="red", value="kkk", arrayAttr={1,2,3}, 
              annotation=@MetaAnnotation("llllll"))
public class AnnotationTest {
    
    @MyAnnotation("xyz")
    public static void main(String[] args) {
        System.runFinalizersOnExit(true);
        //判断类有没有指定注解
        if (AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation annotaion = AnnotationTest.class.getAnnotaion(MyAnnotation.class);
            System.out.println(annotaion);
            //输出注解中的参数
            System.out.println(annotation.color());
            System.out.println(annotation.value());
            System.out.println(annotation.arrayAttr().length);
            System.out.println(annotation.annotation().value());
        }
    }
    
}

输出结果:

@com.reflection.MyAnnotation(color=red, annotation=@com.reflection.MetaAnnotation(value=fllll), arrayAttr=[1, 2, 3], value=kkk)
red
kkk
3
llllll

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐江小鱼

知识创造财富,余额还是小数

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值