标题
创建一个注解类
import javax.annotation.Resource;
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 Car {
public String price(int money){
return "玛莎拉蒂"+money;
}
}
创建一个测试类
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
@MyZhuJie(pathName = “com.itheima03.Car”,methodName = “price”)
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 name = Class.forName(pathName);
//创建对象,构造方法的简化用法
Object o = name.newInstance();
//获取方法的对象
Method method = name.getDeclaredMethod(methodName,int.class);
//强制访问
method.setAccessible(true);
//调用方法
Object result = method.invoke(o,180000);
//打印结果
System.out.println(result);