為什么要學(xué)習(xí)注解
- 看懂別人的代碼
- 會(huì)用注解 編程簡潔 代碼清晰
- 讓別人高看一眼(會(huì)自定義注解)
注解的概念
Java 提供了一種原程序中的元素關(guān)聯(lián)任何信息和任何元數(shù)據(jù)的途徑和方法。
Java中的常見注解
@Override
@De
注解的分類
- 源碼注解:注解只在源碼中存在,編譯稱.class 文件就不存在了巡莹。
- 編譯時(shí)注解:注解在源碼和編譯文件中都存在话浇。
- 運(yùn)行時(shí)注解:在運(yùn)行階段仍舊起作用,甚至?xí)绊戇\(yùn)行邏輯的注解癣诱。
- 元注解:注解的注解
自定義注解的語法要求
- 類使用@interface 關(guān)鍵字定義注解
- 注解的成員類型是受限的墓拜,合法的類型包括原始類型及String,Class,Annotation,Enumeration
- 如果注解只有一個(gè)成員蚁飒,則成員名必須為value() ,在使用時(shí)可以忽略成員名和賦值號(=)
- 注解可以沒有成員,稱為標(biāo)示注解
public @interface Description{
String desc(); // 成員無參 無異常拋出
String author();
int age() default 18;
}
元注解
@Target({ElementType.METHOD,ElementType.TYPE})// 注解的作用域
@Retention(RetentionPolicy.RUNTIME)// 生命周期 source class runtime
@Inherited // 允許子類繼承
@Documented // 生成 javadoc 的時(shí)候會(huì)包含注解信息
public @interface Description {
String desc();
String author();
int age() default 18;
}
使用自定義注解
@<注解名>(<成員名1>=<成員值1>,<成員名2>=<成員名2>,...)
@Description(desc = "I am eyeColor",author = "Somebody",age = 18)
public String eyeColor(){
return "red";
}
解析注解
通過反射獲取類锅风、函數(shù)或成員上的運(yùn)行時(shí)注解信息酥诽,從而實(shí)現(xiàn)動(dòng)態(tài)控制程序運(yùn)行的邏輯。
public class ParseAnn {
public static void main(String[] args){
// 1. 使用類加載器加載類
try {
Class c = Class.forName("MapDemo");
//2 找到類上面的注解
boolean isExist = c.isAnnotationPresent(Description.class);
if (isExist){
// 3. 拿到注解實(shí)例
Description d = (Description) c.getAnnotation(Description.class);
System.out.print(d.desc());
}
// 4. 找到方法上的注解
Method[] ms = c.getMethods();
for (Method m:ms
) {
boolean isMExist = m.isAnnotationPresent(Description.class);
if (isMExist){
Description d = m.getAnnotation(Description.class);
System.out.print(d.desc());
}
}
for (Method m:ms
) {
Annotation[] as = m.getAnnotations();
for (Annotation a: as
) {
if (a instanceof Description){
Description d = (Description) a;
System.out.print(d.desc());
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}