package com.example.demo.bibi;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD) // 自定义注解加在什么地方
@Retention(RetentionPolicy.RUNTIME) // 只能在运行时执行
public @interface MyTest {
String name();
int age() default 18;
String[] likes();
}
package com.example.demo.bibi;
public class MyTestDemo {
@MyTest(name = "zhan", age = 19, likes = {"吃饭", "睡觉"})
public void one() {
}
}
package com.example.demo.bibi;
import java.lang.reflect.Method;
/**
* @author wenhui
* @description
* @Date 2022/6/30
*/
public class MyTestMain {
public static void main(String[] args) throws ClassNotFoundException {
//通过字节码获取类对象
//Class<MyTest> myTestClass = MyTest.class;
Class<?> aClass = Class.forName("com.example.demo.bibi.MyTestDemo");
//获取对象的所有方法
Method[] methods = aClass.getMethods();
for (Method method : methods) {
//遍历方法里是否有自定义注解
boolean b = method.isAnnotationPresent(MyTest.class);
//分析注解里面的参数
if(b) {
MyTest myTest = method.getAnnotation(MyTest.class);
System.out.println(method.getName()+"==="+myTest);
} else {
System.out.println(method.getName()+"===没有自定义注解");
}
}
}
}
输出: