首页 > 其他 > 详细

查看JDK自动生成的代理类源码

时间:2018-12-25 00:00:26      阅读:281      评论:0      收藏:0      [点我收藏+]

直接运行下面的代码,在D盘就可以看到生成的源码类$GameProxy.class

import sun.misc.ProxyGenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 查看JDK自动生成的代理类源码
 *
 * @author sky
 */
public class ViewProxyClass {
    public static void main(String[] args) throws Exception {
        Moveable huiXiong = new Tank("灰熊坦克");
        ClassLoader classLoader = huiXiong.getClass().getClassLoader();
        Class<?>[] interfaces = huiXiong.getClass().getInterfaces();
        Moveable proxy = (Moveable) Proxy.newProxyInstance(classLoader, interfaces, new TimeInvocationHandler(huiXiong));
        System.out.println(proxy.getClass());
        proxy.move();

        byte[] bts = ProxyGenerator.generateProxyClass("$GameProxy", interfaces);
        FileOutputStream fos = new FileOutputStream(new File("D:/$GameProxy.class"));
        fos.write(bts);
        fos.flush();
        fos.close();
    }
}

interface Moveable {
    public void move();
    public void stop();
    public String getName();
}

class Tank implements Moveable {
    private String name;
    public Tank(String name) {
        this.name = name;
    }
    @Override
    public String getName() {
        return name;
    }
    @Override
    public void stop() {
        System.out.println(this.name + " stop ...");
    }
    @Override
    public void move() {
        System.out.println(this.name + " run ...");
    }
}

class TimeInvocationHandler implements InvocationHandler {
    private Moveable target;
    public TimeInvocationHandler(Moveable target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("被代理");
        method.invoke(target, args);
        System.out.println("被代理");
        return proxy;
    }
}

 

查看JDK自动生成的代理类源码

原文:https://www.cnblogs.com/Mike_Chang/p/10171721.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!