檢視JDK自動生成的代理類原始碼
阿新 • • 發佈:2018-12-25
直接執行下面的程式碼,在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 classViewProxyClass { 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, newTimeInvocationHandler(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; } }