自定义注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation {
/**
* 只使用一个变量是默认为value
*/
String value() default "";
/**
* 注解的成员变量的类型是受限的,
* 合法的类型包括:原始类型、String、Class、Annotation、Enum
*/
int num() default 1;
}
元注解(对注解进行注解的注解):
- @Target
ElementType.PACKAGE 包声明
ElementType.TYPE 类、接口声明
ElementType.CONSTRUCTOR 构造方法声明
ElementType.METHOD 方法声明
ElementType.FIELD 字段声明
ElementType.PARAMETER 参数声明
- @Retention
RetentionPolicy.RUNTIME 运行时存在 可以通过反射获取
RetentionPolicy.CLASS 编译时存在 运行时忽略
RetentionPolicy.SOURCE 只在源码中显示 编译时丢弃
-
@Inherited
允许子类继承 -
@Documented
生成javadoc时会包含该注解
注解有传递性
解析
- 定义一个类
@MyAnnotation("userClass")
public class User {
@MyAnnotation(value = "id annotation", num = 66)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@MyAnnotation(value = "getName annotation")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 解析
package morning.cat.annotation;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class AnnotationTest {
@Test
public void test1() {
Class<User> clazz = User.class;
// 获取类上注解
Annotation[] annotationArr = clazz.getAnnotations();
for (Annotation annotation : annotationArr) {
if (annotation instanceof MyAnnotation) {
MyAnnotation mya = (MyAnnotation) annotation;
System.out.println(mya.value() + " - " + mya.num());
}
}
}
@Test
public void test2() {
Class<User> clazz = User.class;
Method[] methods = clazz.getMethods();
// 查找方法上的MyAnnotation注解
// 方法1
for (Method method : methods) {
boolean flag = method.isAnnotationPresent(MyAnnotation.class);
if (flag) {
MyAnnotation mya = method.getAnnotation(MyAnnotation.class);
System.out.println(mya.value() + " - " + mya.num());
System.out.println();
}
}
// 方法2
for (Method method : methods) {
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation mya = (MyAnnotation) annotation;
System.out.println(mya.value() + " - " + mya.num());
}
}
}
}
@Test
public void test3() {
Class<User> clazz = User.class;
// 获取私有变量
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
MyAnnotation mya = field.getAnnotation(MyAnnotation.class);
if (mya != null) {
System.out.println(mya.value() + " - " + mya.num());
}
}
}
}