文章目录
注解和反射
1.注解-annotation
1.1 元注解
元注解的作用就是负责注解其他注解(@Target、@Retention、@Documented、@Inherited)
@Target:描述注解的使用范围(方法、类、参数上等)——多个使用范围,必须加上{ }
@Retention: 定义了注解保持有效的 使命周期阶段(runtime(默认写这个) >class>sources)
@Documented: 表示是否将我们的注解生成在JavaDoc中
@Inherited: 子类可以继承父类的注解
//@Retention 定义了注解保持有效的 使命周期阶段
@Retention(RetentionPolicy.RUNTIME)
//@Target 表示注解能使用的目标
@Target({
ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
//@Documented:表示是否将我们的注解生成在JavaDoc中
@Documented
//@Inherited:子类可以继承父类的注解
@Inherited
public @interface MyAnnotation {
//成员
String userName() default "张三";
int age();
boolean flag() default true;
//枚举
Color color() default Color.RED;
//注解
OtherAnnotation othanno();
}
注意:
-
注解:主要作用就在程序中传值(在运行阶段完成:结合反射使用)
-
在注解中参数可以用default来定义默认值
-
调用自定义自定义注解,注解有一个成员参数可以直接写参数值,注解有多个成员参数,必须用参数名value= ;
-
注解中有默认值,可以不用给其赋值·
-
注解中的成员参数是数组且数组只有一个元素时,{}可以省略,否则{}不能省略
@MyAnnotation(userName = "李四",age = 16,color = Color.RED,othanno = @OtherAnnotation(1)) public class annotationDemo { public static void main(String[] args) { System.out.println(" "); } }
1.2 通过基本反射读取注解
annotationDemo类:设置注解
@MyAnnotation(userName = "王啊五",age = 4,flag = true,color = Color.RED,othanno = @OtherAnnotation(1))
public class annotationDemo {
@MyAnnotation(userName = "李四",age = 5,othanno = @OtherAnnotation(4))
private static void print(@MyAnnotation(age = 1,othanno = @OtherAnnotation(1))String userName,@MyAnnotation(age = 7,userName = "刘六")Integer id){
System.out.println("你好");
}
}
TestGetValue类:分别读取类上、方法上、参数上的注解
public class TestGetValue {
public static void main(String[] args) throws NoSuchMethodException {
Class<TestAnnotation> annotationClass = TestAnnotation.class;
//获取方法参数中的注解
Method print = annotationClass.getDeclaredMethod("print", String.class, Integer.class);
Parameter[] parameters = print.getParameters();
for (Parameter parameter : parameters) {
boolean annotationPresent = parameter.isAnnotationPresent(MyAnnotation.class);
if (annotationPresent) {
MyAnnotation annotation