码迷,mamicode.com
首页 > 其他好文 > 详细

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

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

标签:leo   exce   sys   obj   etc   game   loader   object   gen   

直接运行下面的代码,在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自动生成的代理类源码

标签:leo   exce   sys   obj   etc   game   loader   object   gen   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!