注解的定义
注解是一种能被添加到java源代码中的元数据,可以看做是是一种特殊标记,可以在包、类、参数和方法上使用,可以进行一些特殊的处理。
访问修饰符必须为public,不写默认为public。
元注解
JDK中有一些元注解来修饰注解,主要包括@Target,@Retention,@Document,@Inherited。
@Target:可以应用的java类型
Target |
说明 |
ElementType.TYPE |
应用于类、接口(包括注解类型)、枚举 |
ElementType.FIELD |
应用于属性(包括枚举中的常量) |
ElementType.METHOD |
应用于方法 |
ElementType.PARAMETER |
应用于方法的形参 |
ElementType.CONSTRUCTOR |
应用于构造函数 |
ElementType.LOCAL_VARIABLE |
应用于局部变量 |
ElementType.ANNOTATION_TYPE |
应用于注解类型 |
ElementType.PACKAGE |
应用于包 |
ElementType.TYPE_PARAMETER |
1.8版本新增,应用于类型变量 |
ElementType.TYPE_USE |
1.8版本新增,应用于任何使用类型的语句中(例如声明语句、泛型和强制转换语句中的类型) |
@Retention:表示注解的生命周期
Retention |
说明 |
RetentionPolicy.SOURCE |
编译时被丢弃,不包含在类文件中 |
RetentionPolicy.CLASS |
JVM加载时被丢弃,包含在类文件中,默认值 |
RetentionPolicy.RUNTIME |
由JVM 加载,包含在类文件中,在运行时可以被获取到 |
@Document:表示可以被Javadoc工具文档化
@Inherited:子类也会拥有这个注解
定义一个注解
定义在类上
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestType {
String ClassName();
}
定义在字段上
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestField {
String fieldName();
boolean isFlag() default false;
}
定义在方法上
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestMethod {
String methodName();
}
在类中使用
@TestType(ClassName = "Person")
public class Person {
@TestField(fieldName = "name")
private String name;
@TestField(fieldName = "age",isFlag = true)
private int age;
@TestMethod(methodName = "eat")
public void eat() {
System.out.println("吃饭");
}
}
获取注解
使用反射去解析注解,获取注解里的参数
public class Test {
public static void main(String[] args) {
// 获取反射对象
Class<Person> personClass = Person.class;
// 获取类上的注解
personClass.isAnnotationPresent(TestType.class);
// 获取字段上的注解
Field[] declaredFields = personClass.getDeclaredFields();
// 获取方法的注解
Method[] methods = personClass.getDeclaredMethods();
if (methods != null) {
for (Method m : methods) {
// 判断方法上是否有注解
if (m.isAnnotationPresent(TestMethod.class)) {
// 取到注解的值
String methodName = m.getAnnotation(TestMethod.class).methodName();
System.out.println(m.getName() + "方法使用了TestMethod注解," + "注解的methodName值为:" + methodName);
}
}
}
}
}