1. Target简介
Target:目标元注解,用来限定目标注解可以作用于哪些地方。
-
ANNOTATION_TYPE:作用在注解上,Target修饰的目标注解B,可以用来修饰注解C。
-
CONSTRUCTOR:作用在构造方法上
-
FIELD:作用在变量属性字段上。
-
LOCAL_VARIABLE:作用在局部变量声名上。
-
METHOD:作用在方法上
-
PACKAGE:作用在包名上。
-
PARAMETER:作用在参数上
-
TYPE:任何类型,即上面的类型都可以修饰。
@Target({ElementType.xxx})选择作用的单个位置,ElementType是可以导包省略的。
@Target({xxx、xxx})作用多个位置。
2. 举例使用
-
FieldAnotation只能作用在字段上的一个注解,采用默认的生命周期为CLASS。
package annotation.target; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.CLASS) @Target({ElementType.FIELD}) public @interface FieldAnotation { }
-
MethodAnnotation注解只能作用在方法上,且生命周期默认为CLASS文件。
package annotation.target; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.CLASS) @Target({ElementType.METHOD}) public @interface MethodAnnotation { }
-
FieldMethod注解,可以用在字段、方法上,生命周期为RUNTIME。即JVM运行时可以通过反射动态加载出来。
package annotation.target; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({FIELD, METHOD}) public @interface FieldMethod { }
-
MainClass类,字段age、方法serName都是采用FieldMethod注解修饰的意味着他们可以反射加载获取到。
package annotation.target; public class MainClass { @FieldAnotation //只能用来修饰变量字段 private String name; @FieldMethod //可以用来修饰字段、方法 private int age; @MethodAnnotation //只能用来修饰方法 public String getName() { return name; } @FieldMethod //可以用来修饰字段、方法 public void setName(String name) { this.name = name; } /* @FieldMethod //报错 public MainClass(String name, int age) { this.name = name; this.age = age; } */ }
-
Demo测试类,通过反射来获取到age的注解数目、setName方法的注解数目
package annotation.target; import org.junit.Test; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Demo { @Test public void test() throws ClassNotFoundException { Field[] fields = Class.forName("annotation.target.MainClass").getDeclaredFields(); for(Field f: fields){ f.setAccessible(true); System.out.println(f.getName() + " -> " + f.getDeclaredAnnotations().length); } System.out.println("-----------"); Method[] methods = Class.forName("annotation.target.MainClass").getDeclaredMethods(); for(Method m: methods){ m.setAccessible(true); System.out.println(m.getName() + " -> " + m.getDeclaredAnnotations().length); } } }
-
分析:
-
age字段使用FieldMethod修饰,并且FieldMethod注解是被两个元注解:@Retention(RetentionPolicy.RUNTIME)、@Target({FIELD, METHOD})修饰,意味着FieldMethod注解可以修饰方法并且生存周期为RUNTIME。所以反射的时候加载到的注解数目为1个(即FieldMethod)。
-
Name字段使用FieldAnotation修饰。而FieldAnotation被两个元注解@Retention(RetentionPolicy.CLASS)、@Target({FIELD, METHOD})修饰。意味着FieldAnotation注解只能修饰字段并且生命周期为CLASS,所以JVM反射加载不到。
-
serName方法和getName方法分析同上。
-