关于java自定义注解的本质

  1. 自定义注解本质上是一个接口,默认继承 Annotation 接口类
  2. 反编译后可得:public interface com.example.baseexercise.atInterfaceTest.MyAnnotation extends java.lang.annotation.Annotation{
  3. 注解的属性是接口中的抽象方法
  4. 反编译后可得:public abstract int intvalue();
  5. isAnnotationPresent方法与getAnnotation方法是Field的方法,需要通过class反射获取
/**
 * 注解本质上就是一个接口 默认继承 {@link Annotation}
 * 注解的属性是接口中的抽象方法
 * @author kmChen
 * @Date 2023/6/17 17:09
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface MyAnnotation {

    /**
     * 属性的返回值类型包括:
     * 基本数据类型
     * String
     * 枚举
     * 注解
     * 以上类型的数组
     */

    MyAnnotation2 myAnnotation2();

    int intvalue();

    String strValue();

    /**
     * 反编译获取的代码(javap MyAnnotation.class)
     * public interface com.example.baseexercise.atInterfaceTest.MyAnnotation extends java.lang.annotation.Annotation {
     *   public abstract com.example.baseexercise.atInterfaceTest.MyAnnotation2 myAnnotation2();
     *   public abstract int intvalue();
     *   public abstract java.lang.String strValue();
     * }
     */
}
  1. 测试类:
public class AnnotationTest {

    /**
     * 注解里面放注解
     */
    @MyAnnotation(myAnnotation2 = @MyAnnotation2(value = 3), intvalue = 2, strValue = "3")
    private String testStr;

    @SneakyThrows
    public static void main(String[] args) throws NoSuchFieldException {
        Field field = AnnotationTest.class.getDeclaredField("testStr");
        field.setAccessible(true);
        if (field.isAnnotationPresent(MyAnnotation.class)){
            MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
            System.out.println("我知道MyAnnotation2的value了,值为:"+annotation.myAnnotation2().value());
        }else{
            System.out.println("我啥都不知道");
        }

    }
}
  1. 反编译后的自定义注解
public interface com.example.baseexercise.atInterfaceTest.MyAnnotation extends java.lang.annotation.Annotation {
  public abstract com.example.baseexercise.atInterfaceTest.MyAnnotation2 myAnnotation2();
  public abstract int intvalue();
  public abstract java.lang.String strValue();
}

留言:老婆做了一个小红书账号,全是瓷砖方面的干货,大佬们如果有需求或者有兴趣可以移步了解一下,嘻嘻~

小红书地址,GO GO GO!!!
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值