proxy 代理

  1. proxy动态代理 demo
    //接口
    public interface Student {
    void getStudentName();
    void getStudentAge();
    }
    //实行接口
    public class JuniorStudent implements Student {
    public void getStudentName() {
    System.out.println(“my name is king”);
    }
    public void getStudentAge() {
    System.out.println(“my age is 20”);
    }
    }
    //代理类
    /实现InvocationHandler/
    public class ProxStudent implements InvocationHandler {
    private Student student;
    //创建构造方法赋值
    public ProxStudent(Student student) {
    this.student = student;
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println(“my is proxyStudy”);
    /获取所以代理接口的 方法/
    method.invoke(student,args);
    //获取代理类的某一个方法
    // student.getStudentName();
    System.out.println(“after”);
    return student;
    }
    }

public class Client {
public static void main(String[] args) {
//获取代理的对象
Student student = new JuniorStudent();
//把要代理的对象 传进去 然后获取方法
InvocationHandler handlerStudent =new ProxStudent(student);
/*Proxy.newProxyInstance 创建代理对象
* handler.getClass().getClassLoader() 加载对象
* student.getClass().getInterfaces()获取代理的接口
* handlerStudent 将代理对象Student 关联到 handlerStudent上
* */
Student newProxyInstance = (Student) Proxy.newProxyInstance(handlerStudent.getClass()
.getClassLoader(),student.getClass().getInterfaces(),handlerStudent);
newProxyInstance.getStudentAge();
}

    //创建class字节码文件	可以放在target 查看代码
    		
    try {
        byte[] bytes = ProxyGenerator.generateProxyClass("$ProxyKing",new Class[]{Student.class});
        FileOutputStream fileOutputStream = new FileOutputStream("D:/env/$ProxyKing.class");
        fileOutputStream.write(bytes);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

  1. proxy 源码
    Proxy.newProxyInstance{
    //代理类的缓存
    1. proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
    ProxyClassFactory{
    //在WeakCache的构造方法里 去调用
    apply(){
    interfaceClass = Class.forName(intf.getName(), false, loader);
    //根据包名类名创建代理
    byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
    proxyName, interfaces, accessFlags);{
    ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
    final byte[] var4 = var3.generateClassFile();//创建class 文件返回数组 class也是字节码文件 上吗demo 有
    defineClass0();{//需要吧 byte[]转为class 文件装进jvm 里面
    用native 的方法 //本地方法
    }
    }
    }
    }

    //如果指定的加载器实现了指定的接口,这将简单地返回缓存的副本;//否则,它将通过ProxyClassFactory创建代理类

  2. Class<?> cl = getProxyClass0(loader, intfs){
    return proxyClassCache.get(loader, interfaces);
    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值