透过字节码分析Java动态代理机制。
2020-12-13 04:25
标签:try object nop lang tor sys gen rop rac 一、创建动态代理代码 1、创建接口 2、创建接口实现类 3、创建DynamicSubject类 4、创建测试类 输出结果: 查看源码,动态代理类在ProxyGenerator类的generateProxyClass生成。 可以发现saveGeneratedFiles为true时,可以将代理类保存到磁盘上。 因此在测试类中sun.misc.ProxyGenerator.saveGeneratedFiles属性设置为true 透过字节码分析Java动态代理机制。 标签:try object nop lang tor sys gen rop rac 原文地址:https://www.cnblogs.com/linlf03/p/11109977.htmlpublic interface Subject {
void request();
}
public class RealSubject implements Subject
{
@Override
public void request() {
System.out.println("From real subject");
}
}
public class DynamicSubject implements InvocationHandler {
private Object sub;
public DynamicSubject(Object obj){
this.sub = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before calling:" + method);
method.invoke(this.sub, args);
System.out.println("after calling:" + method);
return null;
}
}
public class Client {
public static void main(String[] args) {
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
RealSubject rs = new RealSubject();
InvocationHandler ds = new DynamicSubject(rs);
Class> cls = rs.getClass();
Subject subject = (Subject) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), ds);
subject.request();
System.out.println(subject.getClass());
System.out.println(subject.getClass().getSuperclass());
}
}
before calling:public abstract void com.example.jvm.bytecode.Subject.request()
From real subject
after calling:public abstract void com.example.jvm.bytecode.Subject.request()
class com.sun.proxy.$Proxy0
class java.lang.reflect.Proxy
public static byte[] generateProxyClass(final String var0, Class>[] var1, int var2) {
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
final byte[] var4 = var3.generateClassFile();
if(saveGeneratedFiles) {
AccessController.doPrivileged(new PrivilegedAction
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
最终生成的.class 文件位置如下图