JAVA - 注解
認識注解
注解(Annotation)
- 就是JAVA 代碼里的特殊標記,比如:@Override,@Test 等,作用是:讓其他程序根據注解信息來決定怎么執行該程序。
- 注意:注解可以用在類上、構造器上、方法上、成員變量上、參數上、等位置處

自定義注解
- 就是自己定義注解

特殊屬性名稱:value
- 如果注解中只有一個value屬性,使用注解時,value 名稱可以不寫
注解的原理

- 注解本質是一個接口,Java 中所有的注解都是繼承了Annotation接口的
- @注解(...): 其實就是一個實現類對象,實現了該注解以及Annotation 接口
元注解
- 指的是:修飾注解的注解

注解解析
什么是注解解析?
- 就是判斷類上,方法上,成員變量上是否存在注解,并把注解里面的內容解析出來。
如何解析注解?
- 要解析誰上面的注解,就應該先拿到誰。
- 比如要解析類上面的注解,則應該先獲取該類的Class對象,再通過Class對象解析其上面的注解
- 比如要解析成員方法上的注解,則應該獲取該成員方法上的Method對象,再通過Method對象解析其上面的注解
- Class、Method、Field、Constructor 都實現了AnnotatedElement接口,它們都擁有解析注解的能力。

解析案例:
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());
}
}
}
本文來自博客園,作者:chuangzhou,轉載請注明原文鏈接:http://www.rzrgm.cn/czzz/p/19030519

浙公網安備 33010602011771號