探索jdk反射思路反射工具使用

public static TestService createProxy1() throws Exception {
    // 1 创建一个类
    ClassPool classPool = new ClassPool();
    classPool.appendSystemPath();
    CtClass proxy = classPool.makeClass("TestServiceImpl");
    proxy.addInterface(classPool.get(TestService.class.getName()));
    // 2 创建一个方法
    CtMethod sayHello = CtNewMethod.make(CtClass.voidType, "sayHello1", new CtClass[]{classPool.get(String.class.getName())}, new CtClass[0], "{System.out.println(\"hello:\" + $1);}", proxy);
    proxy.addMethod(sayHello);
    // 3 实例化类
    Class aClass = classPool.toClass(proxy);
    return (TestService) aClass.getDeclaredConstructor().newInstance();
}

static int num = 0;
public static <T> T createProxy2(Class<T> classInterface, invocationHandler invocation) throws Exception {
    // 创建一个类
    ClassPool classPool = new ClassPool();
    classPool.appendSystemPath();
    CtClass proxy = classPool.makeClass("proxy" + num);
    proxy.addInterface(classPool.get(classInterface.getName()));
    proxy.addField(CtField.make("public ProxyService.invocationHandler handler=null;", proxy));
    for (Method method : classInterface.getMethods()) {

        CtClass[] parameters = Arrays.stream(method.getParameterTypes()).map(e -> {
            try {
                return classPool.get(e.getName());
            } catch (NotFoundException ex) {
                throw new RuntimeException(ex);
            }
        }).toArray(CtClass[]::new);


        CtClass[] exceptions = Arrays.stream(method.getExceptionTypes()).map(e -> {
            try {
                return classPool.get(e.getName());
            } catch (NotFoundException ex) {
                throw new RuntimeException(ex);
            }
        }).toArray(CtClass[]::new);

        CtClass ctClass = classPool.get(method.getReturnType().getName());

        String src;

        if (method.getReturnType() == void.class) {
            src = "this.handler.invoke(\"%s\",$args);";
        } else {
            src = "return ($r)this.handler.invoke(\"%s\",$args);";
        }

        proxy.addMethod(CtNewMethod.make(ctClass, method.getName(), parameters, exceptions, String.format(src, method.getName()), proxy));
    }

    Class aClass = classPool.toClass(proxy);
    T o = (T) aClass.getDeclaredConstructor().newInstance();
    aClass.getField("handler").set(o, invocation);
    return o;
}

public static void main(String[] args) throws Exception {
    TestService proxy = createProxy2(TestService.class, new invocationHandler() {

        @Override
        public void invoke(String name, Object[] args) {
            System.out.println("hello " + Arrays.toString(args));
        }
    });
    proxy.sayHello2("111");
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值