查看JDK自动生成的代理类源码
Posted mike_chang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了查看JDK自动生成的代理类源码相关的知识,希望对你有一定的参考价值。
直接运行下面的代码,在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自动生成的代理类源码的主要内容,如果未能解决你的问题,请参考以下文章