java 动态代理

下面就直接给出例子:

//利用JDK的InvocationHandler和Proxy
    private class MyInvocationHandler implements InvocationHandler {
        private Object o;
        
        MyInvocationHandler(Object o) {
            this.o = o;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            ...//插入自己的操作
            method.invoke(mvpView, args);//调用 代理类的方法
            ...//插入自己的操作
        }
    }
    
    InvocationHandler handler = new MyInvocationHandler();
    MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
                            MyInterface.class.getClassLoader(),
                            new Class[] { MyInterface.class },
                            handler);

实际应用中都是直接调用 JDK 的 Proxy.newProxyInstance ,不过我们可以了解一下它的底层原理。


1. 底层模拟动态代理

package dynamicProxy;
import java.lang.reflect.Method;

public interface InvocationHandler {
    void invoke(Object proxy, Method method);
}
-------------------------------------------------------------------------------------------

package dynamicProxy;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 功能:
 */
public class Proxy {

    public static Object newProxyInstance(Class interfaces,InvocationHandler invocationHandler) throws Exception {

        String methodStr="";
        String rt = "\r\n";

        Method[] methods=interfaces.getMethods();
        for (Method m: methods){

            methodStr+= "    @Override" + rt +
                        "    public "+m.getReturnType().getName()+" "+m.getName()+"("+" "+") {"+rt+
                        "           try{"+rt+
                        "               Method md = "+interfaces.getName()+".class.getMethod(\""+m.getName()+"\");"+rt+
                       /* "           "+invocationHandler.invoke(this,"md");+rt+*/
                        "               handler.invoke(this,md);" +rt+
                        "           }catch (NoSuchMethodException e) {\n" +
                        "               e.printStackTrace();\n" +
                        "           }"+rt+
                        "    }";

        }

        String src =    "package dynamicProxy;" + rt +

                        "import java.lang.reflect.Method;" + rt +

                        "public class $Proxy1 implements " + interfaces.getName() + "{" + rt +
                        "    dynamicProxy.InvocationHandler handler;" +rt+
                        "    public $Proxy1(dynamicProxy.InvocationHandler handler) {" + rt +
                        "        super();" + rt +
                        "        this.handler = handler;" + rt +
                        "    }" + rt +
                        methodStr + rt +
                        "}";

        String fileName = System.getProperty("user.dir")
                + "/src/dynamicProxy/$Proxy1.java";


        //在/src/dynamicProxy下动态创建TankTimeProxy.java文件
        File f = new File(fileName);
        FileWriter fileWriter = new FileWriter(f);
        fileWriter.write(src);
        fileWriter.flush();
        fileWriter.close();

        //编译动态生成的java文件
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(null, null, null);
        Iterable units = fileManager.getJavaFileObjects(fileName);
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager,
                null, null, null, units);
        task.call(); //进行编译
        fileManager.close();

        //把编译完成的.class文件加载进内存中并创建实例
        URL[] urls = new URL[]{new URL("file:/" + System.getProperty("user.dir"))};
        URLClassLoader urlClassLoader = new URLClassLoader(urls);
        Class c = urlClassLoader.loadClass("dynamicProxy.$Proxy1"); //报错是因为配置的原因
        System.out.println(c);

        Constructor constructor=c.getConstructor(InvocationHandler.class);
        return constructor.newInstance(invocationHandler);
    }
}

例子如下:

public interface Moveable {
    void move();
}


/**
 * 功能:看作是第三方不可修改的类
 */
public class Tank implements Moveable {
    @Override
    public void move() {
        System.out.println("正在移动");
        try {
            new Thread().sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在不修改源码的情况下,对move方法进行时间计算(在move前后进行自己的操作)

/**
 * 功能:处理类
 */
public class TimeHandler implements InvocationHandler{

    Object object;

    public TimeHandler(Object object){
        super();
        this.object=object;
    }

    @Override
    public void invoke(Object proxy, Method method) {
        long start=System.currentTimeMillis();
        System.out.println("startTime: "+start);
        try {
            // !!! 注意,这里m.invoke执行的对象,应该是外界传入的object,如tank
            method.invoke(object,new Object[]{});
        } catch (Exception e) {
            e.printStackTrace();
        }
        long end=System.currentTimeMillis();
        System.out.println("time: "+(end-start));
    }
}

//测试类
public class Text {
    public static void main(String[] args) throws Exception {

        Tank tank=new Tank();
        InvocationHandler handler=new TimeHandler(tank);
                Moveable m= (Moveable) Proxy.newProxyInstance(Moveable.class,handler);
        m.move();
    }
}

//log
class dynamicProxy.$Proxy1
startTime: 1520388195900
正在移动
time: 215

这样做,最明显的好处就是 Proxy类不用修改,会动态生成与代理类具有相同方法的$Proxy1类,通过实现InvocationHandler的方法,就能对代理类(此类是Tank),增加操作.
动态生成的代码如下:

package dynamicProxy;
import java.lang.reflect.Method;
public class $Proxy1 implements interfaces.Moveable{
    dynamicProxy.InvocationHandler handler;
    public $Proxy1(dynamicProxy.InvocationHandler handler) {
        super();
        this.handler = handler;
    }
    @Override
    public void move( ) {
           try{
               Method md = interfaces.Moveable.class.getMethod("move");
               handler.invoke(this,md);
           }catch (NoSuchMethodException e) {
               e.printStackTrace();
           }
    }
}

2. 分析底层模拟动态代理

Moveable m= (Moveable) Proxy.newProxyInstance(Moveable.class,handler);
-->

public static Object newProxyInstance(Class interfaces,InvocationHandler invocationHandler) throws Exception {

        ...
        Class c = urlClassLoader.loadClass("dynamicProxy.$Proxy1"); //报错是因为配置的原因
        System.out.println(c);
        Constructor constructor=c.getConstructor(InvocationHandler.class);
        return constructor.newInstance(invocationHandler);
    }
    
其中c是生成的代理类 $Proxy1,所以 Proxy.newProxyInstance(Moveable.class,handler); 最终就是返回 $Proxy1 对象
package dynamicProxy;
import java.lang.reflect.Method;
public class $Proxy1 implements interfaces.Moveable{
    dynamicProxy.InvocationHandler handler;
    public $Proxy1(dynamicProxy.InvocationHandler handler) {
        super();
        this.handler = handler;
    }
    @Override
    public void move( ) {
           try{
               Method md = interfaces.Moveable.class.getMethod("move");
               handler.invoke(this,md);
           }catch (NoSuchMethodException e) {
               e.printStackTrace();
           }
    }
}
--> 

所以 m.move(),实际就是调用 
$Proxy1.move(){
    ...
    Method md = interfaces.Moveable.class.getMethod("move");
    handler.invoke(this,md); //就是调用handler的invoke方法
}
-->

public class TimeHandler implements InvocationHandler{
    Object object;
    public TimeHandler(Object object){
        super();
        this.object=object;
    }
    @Override
    public void invoke(Object proxy, Method method) {
        ...//your action
            // 注意!!!,第一个参数是调用外界 需要代理的类
            method.invoke(object,new Object[]{});
        ...//your action
    }
}
-->

而
    Tank tank=new Tank();
    InvocationHandler handler=new TimeHandler(tank);
    所以,handler里面的  method.invoke(object,new Object[]{}); 相当于调用了 tank.move();

由此可见,动态代理能实现 在每个方法前后 判空,权限检查,打印LOG等等操作.


参考:
详细介绍: 10分钟看懂动态代理设计模式
简洁介绍: Java 动态代理
代码来源: 马士兵的设计模式--java动态代理(视频)

你可能感兴趣的:(java 动态代理)