JAVA中自定义注解与反射
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定义一个注解(需要添加元注解,使用范围,使用时机)
@Target(ElementType.TYPE) //使用范围 可以在类,方法 ,变量上面定义
@Retention(RetentionPolicy.RUNTIME) //使用时机:运行代码时
public @interface MyZhuJie {
//定义属性,加上小括号
String pathName();
String methodName();
}
public class Cat {
//使用成员方法
private String say(int num){
return "猫吃"+num+"条鱼";
}
}
import java.lang.reflect.Method;
@MyZhuJie(pathName ="com.xiong.Cat",methodName = "say")
public class Test {
public static void main(String[] args) throws Exception{
//【1】采用当前类的字节码对象 获取注解的对象
MyZhuJie zhujie = Test.class.getAnnotation(MyZhuJie.class);
//【2】获取到里面的数据
String pathName = zhujie.pathName();
String methodName = zhujie.methodName();
//=====================================
//获取字节码对象
Class clazz = Class.forName(pathName);
//创建对象 构造方法的简化用法
Object o = clazz.newInstance();
//获取方法的对象
Method m = clazz.getDeclaredMethod(methodName,int.class);
//暴力访问
m.setAccessible(true);
//调用方法
Object result = m.invoke(o, 66);
//打印输出结果
System.out.println("result = " + result);
}
}