进阶day12-注解解析相关API

This commit is contained in:
2026-04-02 14:17:14 +08:00
parent 168fb05eb3
commit 435a8d85c3
4 changed files with 74 additions and 2 deletions

View File

@@ -1,4 +1,4 @@
package com.inmind;
package com.inmind.annotation03;
/*
元注解:用来修饰注解的注解
@Target:设置某一个注解的作用范围

View File

@@ -0,0 +1,67 @@
package com.inmind.annotation03;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
Anontation所有注解类型的公共接口类似所有类的父类是Object。
AnnotatedElement接口定义了与注解解析相关的方法常用方法以下四个
1. boolean isAnnotationPresent(Class annotationClass);
判断当前对象是否有指定的注解有则返回true否则返回false。
2. T getAnnotation(Class<T> annotationClass);
获得当前对象上指定的注解对象。
3. Annotation[] getAnnotations();
获得当前对象及其从父类上继承的所有的注解对象。
4. Annotation[] getDeclaredAnnotations();
获得当前对象上所有的注解对象,不包括父类的。
注意我们之前学习的所有的反射API基本都是实现了AnnotatedElement接口反射API都可解析注解
*/
public class Demo09 {
public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
/*
需求:
1.使用反射获取私有的show方法上的MyAnnotation的注解的value属性值
2.将value的值作为show方法的参数让show方法执行起来
解析:
1.获取私有的show方法的Method对象
2.判断下该show方法上是否有MyAnnotation注解
3.如果有该注解获取MyAnnotation的注解对象并获取注解中的value属性值
4.调用Mehotd对象的invoke方法将value的值作为参数执行起来
*/
//1.获取私有的show方法的Method对象
Class<Student> clazz = Student.class;
Method showMethod = clazz.getDeclaredMethod("show", int.class);
/*
2.判断下该show方法上是否有MyAnnotation注解
boolean isAnnotationPresent(Class annotationClass);判断当前对象是否有指定的注解有则返回true否则返回false。
*/
boolean flag = showMethod.isAnnotationPresent(MyAnnotation.class);
System.out.println(flag);
/*
3.如果有该注解获取MyAnnotation的注解对象并获取注解中的value属性值
T getAnnotation(Class<T> annotationClass);获得当前对象上指定的注解对象
*/
if (flag) {
MyAnnotation annotation = showMethod.getAnnotation(MyAnnotation.class);
int value = annotation.value();
System.out.println(value);
/*
4.调用Mehotd对象的invoke方法将value的值作为参数执行起来
*/
showMethod.setAccessible(true);
Object result = showMethod.invoke(clazz.newInstance(), value);
System.out.println(result);
}
}
}

View File

@@ -1,6 +1,8 @@
package com.inmind.annotation03;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
@@ -21,6 +23,7 @@ import java.util.ArrayList;
6.注解在使用时,属性值必须赋值,默认值可以覆盖
*/
@Target(value = {ElementType.TYPE,ElementType.FIELD,ElementType.METHOD,ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)//让当前的注解在运行时也有效,便于反射技术
public @interface MyAnnotation {
public static final int age = 1;//注解中的常量
String name() default "张三";//name属性

View File

@@ -1,5 +1,7 @@
package com.inmind.annotation03;
import org.junit.Test;
@MyAnnotation(name = "李四",value = 1)
public class Student {
//属性(成员变量)
@@ -24,7 +26,7 @@ public class Student {
System.out.println("无参无返回值的show方法执行了");
}
@MyAnnotation(1)
@MyAnnotation(100)
private int show(int i){
System.out.println("有参有返回值的show方法执行了");
return i+100;