一悦荒、注解基礎(chǔ)
1.注解的定義
Java文件叫做Annotation,用@interface
表示垛贤。
2.元注解 修飾注解的注解
@interface
上面按需要注解上一些東西真朗,包括@Retention、@Target燃领、@Document士聪、@Inherited
四種。
@Retention 保留策略
@Retention(RetentionPolicy.SOURCE) // 注解僅存在于源碼中猛蔽,在class字節(jié)碼文件中不包含
@Retention(RetentionPolicy.CLASS) // 默認(rèn)的保留策略剥悟,注解會在class字節(jié)碼文件中存在,但運(yùn)行時(shí)無法獲得
@Retention(RetentionPolicy.RUNTIME) // 注解會在class字節(jié)碼文件中存在曼库,在運(yùn)行時(shí)可以通過反射獲取到
@Target 注解的作用目標(biāo):
@Target(ElementType.TYPE) // 接口区岗、類、枚舉毁枯、注解
@Target(ElementType.FIELD) // 字段慈缔、枚舉的常量
@Target(ElementType.METHOD) // 方法
@Target(ElementType.PARAMETER) // 方法參數(shù)
@Target(ElementType.CONSTRUCTOR) // 構(gòu)造函數(shù)
@Target(ElementType.LOCAL_VARIABLE) // 局部變量
@Target(ElementType.ANNOTATION_TYPE) // 注解
@Target(ElementType.PACKAGE) // 包
注解包含在javadoc中:
@Documented
注解可以被繼承:
@Inherited
3.注解解析器:用來解析自定義注解。
二后众、注解使用
案例一
自定義注解類
import java.lang.annotation.*;
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Init {
public String value() default "null";
}
使用類
public class User {
@Init("李三")
public String name;
@Init("23")
public String arg;
}
解析
通過反射胀糜,獲取自定義注解的值
import java.lang.reflect.Field;
public class Zhujie {
public static void main(String[] args) {
User user = new User();
Field[] fields = User.class.getFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Init.class)) {
Init annotation = field.getAnnotation(Init.class);
String name = field.getName();
String value = annotation.value();
System.out.println("name = " + name + ", value = " + value);
try {
field.set(user, annotation.value());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
System.out.println("user = " + user.toString());
}
}