java代理(静态代理和动态代理)

我们根据加载被代理类的时机不同,将代理分为静态代理和动态代理。如果我们在代码编译时就确定了被代理的类是哪一个,那么就可以直接使用静态代理;如果不能确定,那么可以使用类的动态加载机制,在代码运行期间加载被代理的类这就是动态代理,比如RPC框架和Spring AOP机制。

本文介绍如下三种代理:
JDK静态代理、JDk动态代理、CGLIB动态代理

一、静态代理


public interface Person {
    public void sayHello(String content, int age);
    public void sayGoodBye(boolean seeAgin, double time);
}


public class Student implements Person{
 
    @Override
    public void sayHello(String content, int age) {
        // TODO Auto-generated method stub
        System.out.println("student say hello" + content + " "+ age);
    }
 
    @Override
    public void sayGoodBye(boolean seeAgin, double time) {
        // TODO Auto-generated method stub
        System.out.println("student sayGoodBye " + time + " "+ seeAgin);
    }
 
}


public class ProxyTest implements Person{
    private Person o;
    
    public ProxyTest(Person o){
        this.o = o;
    }
    public void sayHello(String content, int age) {
        // TODO 自动生成的方法存根
        System.out.println("ProxyTest sayHello begin");
        //在代理类的方法中 间接访问被代理对象的方法
        o.sayHello(content, age);
        System.out.println("ProxyTest sayHello end");
    }

    public void sayGoodBye(boolean seeAgin, double time) {
        // TODO 自动生成的方法存根
        System.out.println("ProxyTest sayHello begin");
        //在代理类的方法中 间接访问被代理对象的方法
        o.sayGoodBye(seeAgin, time);
        System.out.println("ProxyTest sayHello end");
    }

}


public class Client {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        //s为被代理的对象,某些情况下 我们不希望修改已有的代码,我们采用代理来间接访问
        Student s = new Student();
        //创建代理类对象
        ProxyTest proxy = new ProxyTest(s);
        //调用代理类对象的方法
        proxy.sayHello("welcome to java", 20);
        System.out.println("******");
        //调用代理类对象的方法
        proxy.sayGoodBye(true, 100);
    }

}


运行结果:
ProxyTest sayHello begin
student say hellowelcome to java 20
ProxyTest sayHello end
******
ProxyTest sayHello begin
student sayGoodBye 100.0 true
ProxyTest sayHello end

二、动态代理

我们先直接上动态代理的代码,之后再分析代码的行为,上面的Person接口和Student被代理类保持不变
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler{
    private Object object;
    
    public MyInvocationHandler(Object object){
        this.object = object;
    }
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        // TODO 自动生成的方法存根
        System.out.println("MyInvocationHandler invoke begin");
        System.out.println("proxy: "+ proxy.getClass().getName());
        System.out.println("method: "+ method.getName());
        for(Object o : args){
            System.out.println("arg: "+ o);
        }
        //通过反射调用 被代理类的方法
        method.invoke(object, args);
        System.out.println("MyInvocationHandler invoke end");
        return null;
    }

}


import java.lang.reflect.Proxy;

public class Client2 {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        //创建需要被代理的类
        Student s = new Student();
        //这一句是生成代理类的class文件,前提是你需要在工程根目录下创建com/sun/proxy目录,不然会报找不到路径的io异常
        //System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
        //获得加载被代理类的 类加载器
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        //指明被代理类实现的接口
        Class<?>[] interfaces = s.getClass().getInterfaces();
        // 创建被代理类的委托类,之后想要调用被代理类的方法时,都会委托给这个类的invoke(Object proxy, Method method, Object[] args)方法
        MyInvocationHandler h = new MyInvocationHandler(s);
        //生成代理类
        Person proxy = (Person)Proxy.newProxyInstance(loader, interfaces, h);
        //通过代理类调用 被代理类的方法
        proxy.sayHello("yujie.wang", 20);
        proxy.sayGoodBye(true, 100);
        System.out.println("end");

              /*或者
                //创建需要被代理的类
                Student s = new Student();
                // 创建被代理类的委托类,之后想要调用被代理类的方法时,都会委托给这个类的invoke(Object proxy, Method method, Object[] args)方法
        InvocationHandler handler = new MyInvocationHandler(s);
                //生成代理类
        Person p = (Person) Proxy.newProxyInstance(handler.getClass().getClassLoader(), s.getClass().getInterfaces(), handler);
/*
         * 通过Proxy的newProxyInstance方法来创建我们的代理对象,我们来看看其三个参数
         * 第一个参数 handler.getClass().getClassLoader() ,我们这里使用handler这个类的ClassLoader对象来加载我们的代理对象
         * 第二个参数realSubject.getClass().getInterfaces(),我们这里为代理对象提供的接口是真实对象所实行的接口,表示我要代理的是该真实对象,这样我就能调用这组接口中的方法了
         * 第三个参数handler, 我们这里将这个代理对象关联到了上方的 InvocationHandler 这个对象上
         */
                //通过代理类调用 被代理类的方法
        p.sayHello("yujie.wang", 20);
        p.sayGoodBye(true, 100);*/
    }

}

运行结果:
MyInvocationHandler invoke begin
proxy: com.sun.proxy.$Proxy0
method: sayHello
arg: yujie.wang
arg: 20
student say helloyujie.wang 20
MyInvocationHandler invoke end
MyInvocationHandler invoke begin
proxy: com.sun.proxy.$Proxy0
method: sayGoodBye
arg: true
arg: 100.0
student sayGoodBye 100.0 true
MyInvocationHandler invoke end
end

对比上面两种代理的实现,发现很明显的一个区别,就是静态代理中,代理类中已经指明了要被代理的类(也就是Student类,我们就实现了他的接口Person),这个逻辑是在写代码的时候就已经知道,但若写代码的时候不知道要代理哪个类,就只能通过动态代理实现了,动态代理中,代理类中指定的是Object 对象,也就是可以代理任何的类,然后在运行的时候,把Student赋予给代理类(InvocationHandler handler = new MyInvocationHandler(s);),这样就完成了动态代理的过程。

总结一下:
jdk的代理让我们在不直接访问某些对象的情况下,通过代理机制也可以访问被代理对象的方法,这种技术可以应用在很多地方比如RPC框架,Spring AOP机制,但是我们看到jdk的代理机制必须要求被代理类实现某个方法,这样在生成代理类的时候才能知道重新那些方法。这样一个没有实现任何接口的类就无法通过jdk的代理机制进行代理,当然解决方法是使用cglib的代理机制进行代理。

三、cglib动态代理

public class Person {
    public void sayHello(String name, int age){
        System.out.println(name+"的年龄为:"+age);
    };
}

import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class PersonMethodInterceptor implements MethodInterceptor{

    public Object intercept(Object o, Method method, Object[] objects,
            MethodProxy methodProxy) throws Throwable {
        // TODO 自动生成的方法存根
        System.out.println("before:"+method.getName());
        Object object = methodProxy.invokeSuper(o, objects);
        System.out.println("after:"+method.getName());
        return object;
    }

}

import net.sf.cglib.proxy.Enhancer;

public class Client {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        Enhancer enchancer = new Enhancer();
        enchancer.setSuperclass(Person.class);//继承被代理的类
        enchancer.setCallback(new PersonMethodInterceptor());//设置回调
        Person p = (Person) enchancer.create();//生成代理对象
        p.sayHello("caililiang", 20);//在调用代理类中的方法时会被我们实现的方法拦截器进行拦截
    }

}

运行结果:
before:sayHello
caililiang的年龄为:20
after:sayHello

总结:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。