结构在同一个包下面三个文件
注解MyAnnotation
Demo给注解赋值
Test读取注解赋值
1.MyAnnotation类定义注解
package com.atguigu.test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String getValue() default "no description";
}
2.Demo类对注解变量赋值
package com.atguigu.test;
@MyAnnotation(getValue = "annotation on class")
public class Demo {
@MyAnnotation(getValue = "annotation on field434")
public String name;
@MyAnnotation(getValue = "annotation on method")
public void hello() {}
@MyAnnotation()
public void defaultMethod() {}
}
3.反射读取类的注解值
package com.atguigu.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestDemo {
public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
// 获取类上的注解
Class<Demo> clazz = Demo.class;
MyAnnotation annotationOnClass = clazz.getAnnotation(MyAnnotation.class);
System.out.println(annotationOnClass.getValue());
// 获取成员变量上的注解
Field name = clazz.getField("name");
MyAnnotation annotationOnField = name.getAnnotation(MyAnnotation.class);
System.out.println(annotationOnField.getValue());
// 获取hello方法上的注解
Method hello = clazz.getMethod("hello", (Class<?>[]) null);
MyAnnotation annotationOnMethod = hello.getAnnotation(MyAnnotation.class);
System.out.println(annotationOnMethod.getValue());
// 获取defaultMethod方法上的注解
Method defaultMethod = clazz.getMethod("defaultMethod", (Class<?>[]) null);
MyAnnotation annotationOnDefaultMethod = defaultMethod.getAnnotation(MyAnnotation.class);
System.out.println(annotationOnDefaultMethod.getValue());
}
}
4.执行结果
java 框架隐藏了 读取注解值