Java Annotation
一、元注解
1.@Target
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
public enum ElementType {
TYPE,
FIELD,
METHOD,
PARAMETER,
CONSTRUCTOR,
LOCAL_VARIABLE,
ANNOTATION_TYPE,
PACKAGE,
TYPE_PARAMETER,
TYPE_USE
}
标记在注解上,声明注解可以在哪些地方使用
ElementType枚举值:
value | 范围 |
---|---|
ElementType.TYPE | 类、接口、注解和枚举 |
ElementType.FIELD | 字段和枚举的常量 |
ElementType.METHOD | 方法 |
ElementType.PARAMETER | 参数 |
ElementType.CONSTRUCTOR | 构造方法 |
LOCAL_VARIABLE | 局部变量 |
ANNOTATION_TYPE | 注解 |
PACKAGE | 包 |
2.@Retention
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
public enum RetentionPolicy {
SOURCE,
CLASS,
RUNTIME
}
标记在注解上,声明注解作用范围
RetentionPolicy枚举值:
value | 范围 |
---|---|
RetentionPolicy.SOURCE | 在源代码有效 |
RetentionPolicy.CLASS | 在字节码有效 |
RetentionPolicy.RUNTIME | 在运行时有效 |
3.@Documented
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
标记在注解上,说明该注解将输出在javadoc(日志)中
4.@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
标记在注解上,说明子类可以继承父类中的该注解
二、自定义注解
//自定义@MyValue,声明在字段上,标记字段默认值
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyValue {
String value() default "";
}
使用:
public class Person {
@MyValue("张三")
private String name;
@MyValue("18")
private int age;
@MyValue("男")
private String gender;
public Person() {
}
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}