JAVA - 注解

认识注解

注解(Annotation)

  • 就是JAVA 代码里的特殊标记,比如:@Override,@Test 等,作用是:让其他程序根据注解信息来决定怎么执行该程序。
  • 注意:注解可以用在类上、构造器上、方法上、成员变量上、参数上、等位置处

image

自定义注解

  • 就是自己定义注解

image

特殊属性名称:value

  • 如果注解中只有一个value属性,使用注解时,value 名称可以不写

注解的原理

image

  • 注解本质是一个接口,Java 中所有的注解都是继承了Annotation接口的
  • @注解(...): 其实就是一个实现类对象,实现了该注解以及Annotation 接口

元注解

  • 指的是:修饰注解的注解

image

注解解析

什么是注解解析?

  • 就是判断类上,方法上,成员变量上是否存在注解,并把注解里面的内容解析出来。

如何解析注解?

  • 要解析谁上面的注解,就应该先拿到谁。
  • 比如要解析类上面的注解,则应该先获取该类的Class对象,再通过Class对象解析其上面的注解
  • 比如要解析成员方法上的注解,则应该获取该成员方法上的Method对象,再通过Method对象解析其上面的注解
  • Class、Method、Field、Constructor 都实现了AnnotatedElement接口,它们都拥有解析注解的能力。

image

解析案例:

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

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTest {
    String value();
    double aaa()  default 100L;
    String[] bbb();
}



@MyTest(value = "蜘蛛精", aaa=99.5, bbb={"紫霞","牛夫人"})
public class MyTestDemo {

    @MyTest(value = "至尊宝", aaa=100,bbb={"孙悟空","牛魔王"})
    public void run(){
    }
}





import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;

/*
注解解析
 */
public class AnnotationDemo {
    public static void main(String[] args) throws NoSuchMethodException {
        //1.先得到class对象
        Class<MyTestDemo> myTestDemoClass = MyTestDemo.class;
        //2.解析类上的注解
        if(myTestDemoClass.isAnnotationPresent(MyTest.class)){
            MyTest declaredAnnotation = myTestDemoClass.getDeclaredAnnotation(MyTest.class);
            System.out.println(declaredAnnotation.value());
            System.out.println(Arrays.toString(declaredAnnotation.bbb()));
            System.out.println(declaredAnnotation.aaa());
        }


        //2.解析方法上的注解
        Method run = myTestDemoClass.getDeclaredMethod("run");
        if(run.isAnnotationPresent(MyTest.class)){
            MyTest declaredAnnotation = run.getDeclaredAnnotation(MyTest.class);
            System.out.println(declaredAnnotation.value());
            System.out.println(Arrays.toString(declaredAnnotation.bbb()));
            System.out.println(declaredAnnotation.aaa());
        }
    }
}

posted @ 2025-08-10 10:29  chuangzhou  阅读(27)  评论(0)    收藏  举报