当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 对JDK动态代理的模拟实现

对JDK动态代理的模拟实现

2019年10月21日  | 移动技术网IT编程  | 我要评论

对jdk动态代理的模拟

动态代理在jdk中的实现:

iproducer proxyproduec = (iproducer)proxy.newproxyinstance(producer.getclass().getclassloader()
                , producer.getclass().getinterfaces(),new invocationhandler() {
                    
     public object invoke(object proxy, method method, object[] args) throws throwable {
             object rtvalue = null;
             float money = (float)args[0];
             if("saleproduct".equals(method.getname())){
                     rtvalue = method.invoke(producer, money * 0.8f);
               }
                return rtvalue;
               }
      });

来看看newproxyinstance()这个方法在jdk中的定义

public static object newproxyinstance(classloader loader,
                                      class<?>[] interfaces,
                                      invocationhandler h)
    throws illegalargumentexception
{
   ...
}

它需要三个参数:
classloader loader:类加载器,jdk代理中认为由同一个类加载器加载的类生成的对象相同所以要传入一个加载器,而且在代理对象生成过程中也可能用到类加载器。

class<?>[] interfaces:要被代理的类的接口,因为类可以实现多个接口,使用此处给的是class数组。

invocationhandler h:代理逻辑就是通过重写该接口的invoke()方法实现

通过对newproxyinstance()方法的分析我们能可以做出以下分析:

第二个参数class<?>[] interfaces是接口数组,那么为什么需要被代理类的接口?应该是为了找到要增强的方法,因为由jdk实现的动态代理只能代理有接口的类,

2.invocationhandler h:参数通过重写其invoke()方法实现了对方法的增强。我们先来看一下invoke()方法是如何定义的

/**
* 作用:执行的被代理对象的方法都会经过此方法
* @param proxy  代理对象的引用
* @param method 当前执行的方法的对象
* @param args   被代理对象方法的参数
* @return       被代理对象方法的返回值
* @throws throwable
*/
public object invoke(object proxy, method method, object[] args)
        throws throwable;

而想要重新该方法并完成对目标对象的代理,就需要使用method对象的invoke()方法(注:这个方法与invocationhandler 中的invoke方法不同不过invocationhandler 中的invoke方法主要也是为了声明使用method中的invoke()方法)。我们在来看看method中的invoke()方法

public object invoke(object obj, object... args)

这里终于看到我们要代理的对象要写入的位置。

对有以上内容,我们可以做出以下猜想:(说是猜想,但实际jdk的动态代理就是基于此实现,不过其处理的东西更多,也更加全面

proxy.newproxyinstance(..)这个方法的并不参与具体的代理过程,而是通过生成代理对象proxy来调用invocationhandler 中的invoke()方法,通过invoke()方法来实现代理的具体逻辑。

所以我以下模拟jdk动态代理的这个过程,就是基于以上猜想实现,需要写两个内容,一个是生成代理对象的类(我命名为proxyutil),一个实现对代理对象的增强(我命名为myhandler接口)

proxy类

package wf.util;

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.field;
import java.lang.reflect.method;
import java.net.url;
import java.net.urlclassloader;

public class proxyutil {

    /**
     * public userdaoimpl(user)
     * @param targetinf
     * @return
     */
    public static object newinstance(class targetinf,myhandler h){
        object proxy = null;
        string tab = "\t";
        string line = "\n";
        string infname = targetinf.getsimplename();
        string content = "";
        //这里把代理类的包名写死了,但jdk实现的过程中会判断代理的方法是否是public,如果是则其包名是默认的com.sun.proxy包下,而如果方法类型不是public则生产的java文件包名会和要代理的对象包名相同,这是和修饰符的访问权限有关
        string packagename = "package com.google;"+line;
        string importcontent = "import "+targetinf.getname()+";"+line
                +"import wf.util.myhandler;"+line
                +"import java.lang.reflect.method;"+line;
        //声明类
        string clazzfirstlinecontent = "public class $proxy implements "+infname+"{"+line;
        //属性
        string attributecont = tab+"private myhandler h;"+line;
        //构造方法
        string constructorcont = tab+"public $proxy (myhandler h){" +line
                                +tab+tab+"this.h = h;"+line
                                +tab+"}"+line;
        //要代理的方法
        string mtehodcont = "";
        method[] methods = targetinf.getmethods();
        for (method method : methods) {
            //方法返回值类型
            string returntype = method.getreturntype().getsimplename();
//            方法名称
            string methodname = method.getname();
            //方法参数
            class<?>[] types = method.getparametertypes();
            //传入参数
            string argescont = "";
            //调用目标对象的方法时的传参
            string paramtercont = "";
            int flag = 0;
            for (class<?> type : types) {
                string argname = type.getsimplename();
                argescont = argname+" p"+flag+",";
                paramtercont = "p" + flag+",";
                flag++;
            }
            if (argescont.length()>0){
                argescont=argescont.substring(0,argescont.lastindexof(",")-1);
                paramtercont=paramtercont.substring(0,paramtercont.lastindexof(",")-1);
            }
            mtehodcont+=tab+"public "+returntype+" "+methodname+"("+argescont+")throws exception {"+line
                    +tab+tab+"method method = class.forname(\""+targetinf.getname()+"\").getdeclaredmethod(\""+methodname+"\");"+line;

            if (returntype == "void"){
                mtehodcont+=tab+tab+"h.invoke(method);"+line;
            }else {
                mtehodcont+=tab+tab+"return ("+returntype+")h.invoke(method);"+line;
            }
            mtehodcont+=tab+"}"+line;
        }
        content=packagename+importcontent+clazzfirstlinecontent+attributecont+constructorcont+mtehodcont+"}";

//        system.out.println(content);
        //把字符串写入java文件
        file file = new file("d:\\com\\google\\$proxy.java");
        try {
            if (!file.exists()){
                file.createnewfile();
            }
            filewriter fw = new filewriter(file);
            fw.write(content);
            fw.flush();
            fw.close();

            //编译java文件
            javacompiler compiler = toolprovider.getsystemjavacompiler();

            standardjavafilemanager filemgr = compiler.getstandardfilemanager(null, null, null);
            iterable units = filemgr.getjavafileobjects(file);

            javacompiler.compilationtask t = compiler.gettask(null, filemgr, null, null, null, units);
            t.call();
            filemgr.close();
            url[] urls = new url[]{new url("file:d:\\\\")};
            urlclassloader urlclassloader = new urlclassloader(urls);
            class clazz = urlclassloader.loadclass("com.google.$proxy");

            constructor constructor = clazz.getconstructor(myhandler.class);
            proxy = constructor.newinstance(h);

        }catch (exception e){
            e.printstacktrace();
        }
        return proxy;
    }
}

该类会通过string字符串生成一个java类文件进而生成代理对象

补充: 我在实现java文件时把代理类的包名写死了,但jdk实现的过程中会判断代理的方法是否是public,如果是则其包名是默认的com.sun.proxy包下,而如果方法类型不是public则生产的java文件包名会和要代理的对象包名相同,这是和修饰符的访问权限有关

生成的java类为($proxy)

package com.google;
import wf.dao.userdao;
import wf.util.myhandler;
import java.lang.reflect.method;
public class $proxy implements userdao{
    private myhandler h;
    public $proxy (myhandler h){
        this.h = h;
    }
    public void query()throws exception {
        method method = class.forname("wf.dao.userdao").getdeclaredmethod("query");
        h.invoke(method);
    }
    public string query1(string p)throws exception {
        method method = class.forname("wf.dao.userdao").getdeclaredmethod("query1");
        return (string)h.invoke(method);
    }
}

可以看到代理对象其实起一个中专作用,来调用实现代理逻辑的myhandler接口

myhandler实现如下:

package wf.util;

import java.lang.reflect.method;

public interface myhandler {
    //这里做了简化处理只需要传入method对象即可
    public object invoke(method method);
}

其实现类如下

package wf.util;

import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;

public class myhandlerimpl implements myhandler {
    object target;
    public myhandlerimpl(object target){
        this.target=target;
    }

    @override
    public object invoke(method method) {
        try {
            system.out.println("myhandlerimpl");
            return  method.invoke(target);
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (invocationtargetexception e) {
            e.printstacktrace();
        }
        return null;
    }
}

这里对代理对象的传入是通过构造方法来传入。

至此模拟完成,看一下以下结果

package wf.test;

import wf.dao.userdao;
import wf.dao.impl.userdaoimpl;
import wf.proxy.userdaolog;
import wf.util.myhandlerimpl;
import wf.util.myinvocationhandler;
import wf.util.proxyutil;

import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;

public class test {

    public static void main(string[] args) throws exception {
        final userdaoimpl target = new userdaoimpl();
        system.out.println("自定义代理");
        userdao proxy = (userdao) proxyutil.newinstance(userdao.class, new myhandlerimpl(new userdaoimpl()));
        proxy.query();

        system.out.println("java提供的代理");
        userdao proxy1 = (userdao) proxy.newproxyinstance(test.class.getclassloader(), new class[]{userdao.class},
                new myinvocationhandler(new userdaoimpl()));
        proxy1.query();
    }
}

输出:

自定义代理

myhandlerimpl

查询数据库

------分界线----

java提供的代理

proxy

查询数据库

两种方式都实现了代理,而实际上jdk的动态代理的主要思想和以上相同,不过其底层不是通过string来实现代理类的java文件的编写,而jdk则是通过byte[]实现,其生成class对象时通过native方法实现,通过c++代码实现,不是java要讨论的内容。

byte[] proxyclassfile = proxygenerator.generateproxyclass(
    proxyname, interfaces, accessflags);

private static native class<?> defineclass0(classloader loader, string name,
                                                byte[] b, int off, int len);

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网