溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JDK動(dòng)態(tài)代理如何實(shí)現(xiàn)

發(fā)布時(shí)間:2022-09-09 10:04:13 來(lái)源:億速云 閱讀:137 作者:iii 欄目:開發(fā)技術(shù)

這篇“JDK動(dòng)態(tài)代理如何實(shí)現(xiàn)”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“JDK動(dòng)態(tài)代理如何實(shí)現(xiàn)”文章吧。

JDK動(dòng)態(tài)代理的過(guò)程

JDK動(dòng)態(tài)代理采用字節(jié)重組,重新生成對(duì)象來(lái)替代原始對(duì)象,以達(dá)到動(dòng)態(tài)代理的目的。

JDK中有一個(gè)規(guī)范,在ClassPath下只要是$開頭的.class文件,一般都是自動(dòng)生成的。

要實(shí)現(xiàn)JDK動(dòng)態(tài)代理生成對(duì)象,首先得弄清楚JDK動(dòng)態(tài)代理的過(guò)程。

1.獲取被代理對(duì)象的引用,并且使用反射獲取它的所有接口。

2.JDK動(dòng)態(tài)代理類重新生成一個(gè)新的類,同時(shí)新的類要實(shí)現(xiàn)被代理類實(shí)現(xiàn)的所有接口。

3.動(dòng)態(tài)生成Java代碼,新添加的業(yè)務(wù)邏輯方法由一定的邏輯代碼調(diào)用。

4.編譯新生成的Java代碼(.class文件)。

5.重新加載到VM中運(yùn)行。

手寫實(shí)現(xiàn)JDK動(dòng)態(tài)代理

JDK動(dòng)態(tài)代理功能非常強(qiáng)大, 接下來(lái)就模仿JDK動(dòng)態(tài)代理實(shí)現(xiàn)一個(gè)屬于自己的動(dòng)態(tài)代理。

創(chuàng)建MyInvocationHandler接口

參考JDK動(dòng)態(tài)代理的InvocationHandler 接口,創(chuàng)建屬于自己的MyInvocationHandler接口

public interface MyInvocationHandler {
    Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}

創(chuàng)建MyClassLoader類加載器

public class MyClassLoader extends ClassLoader {
    private File classPathFile;
    public MyClassLoader() {
        String classPath = MyClassLoader.class.getResource("").getPath();
        this.classPathFile = new File(classPath);
    }
    @Override
    protected Class<?> findClass(String name) {
        String className = MyClassLoader.class.getPackage().getName() + "." + name;
        if (classPathFile != null) {
            File classFile = new File(classPathFile, name.replaceAll("\\.", "/") + ".class");
            if (classFile.exists()) {
                FileInputStream in = null;
                ByteArrayOutputStream out = null;
                try {
                    in = new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = in.read(buff)) != -1) {
                        out.write(buff, 0, len);
                    }
                    return defineClass(className, out.toByteArray(), 0, out.size());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

創(chuàng)建代理類

創(chuàng)建的代理類是整個(gè)JDK動(dòng)態(tài)代理的核心

public class MyProxy {
    // 回車、換行符
    public static final String ln = "\r\n";
    /**
     * 重新生成一個(gè)新的類,并實(shí)現(xiàn)被代理類實(shí)現(xiàn)的所有接口
     *
     * @param classLoader       類加載器
     * @param interfaces        被代理類實(shí)現(xiàn)的所有接口
     * @param invocationHandler
     * @return 返回字節(jié)碼重組以后的新的代理對(duì)象
     */
    public static Object newProxyInstance(MyClassLoader classLoader, Class<?>[] interfaces, MyInvocationHandler invocationHandler) {
        try {
            // 動(dòng)態(tài)生成源代碼.java文件
            String sourceCode = generateSourceCode(interfaces);
            // 將源代碼寫入到磁盤中
            String filePath = MyProxy.class.getResource("").getPath();
            File f = new File(filePath + "$Proxy0.java");
            FileWriter fw = new FileWriter(f);
            fw.write(sourceCode);
            fw.flush();
            fw.close();
            // 把生成的.java文件編譯成.class文件
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager manage = compiler.getStandardFileManager(null, null, null);
            Iterable iterable = manage.getJavaFileObjects(f);
            JavaCompiler.CompilationTask task = compiler.getTask(null, manage, null, null, null, iterable);
            task.call();
            manage.close();
            // 編譯生成的.class文件加載到JVM中來(lái)
            Class proxyClass = classLoader.findClass("$Proxy0");
            Constructor c = proxyClass.getConstructor(MyInvocationHandler.class);
            //刪除生成的.java文件
            f.delete();
            // 返回字節(jié)碼重組以后的新的代理對(duì)象
            return c.newInstance(invocationHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 動(dòng)態(tài)生成源代碼.java文件
     *
     * @param interfaces 被代理類實(shí)現(xiàn)的所有接口
     * @return .java文件的源代碼
     */
    private static String generateSourceCode(Class<?>[] interfaces) {
        StringBuffer sb = new StringBuffer();
        sb.append(MyProxy.class.getPackage() + ";" + ln);
        sb.append("import " + interfaces[0].getName() + ";" + ln);
        sb.append("import java.lang.reflect.*;" + ln);
        sb.append("public class $Proxy0 implements " + interfaces[0].getName() + "{" + ln);
        sb.append("MyInvocationHandler invocationHandler;" + ln);
        sb.append("public $Proxy0(MyInvocationHandler invocationHandler) { " + ln);
        sb.append("this.invocationHandler = invocationHandler;");
        sb.append("}" + ln);
        for (Method m : interfaces[0].getMethods()) {
            Class<?>[] params = m.getParameterTypes();
            StringBuffer paramNames = new StringBuffer();
            StringBuffer paramValues = new StringBuffer();
            StringBuffer paramClasses = new StringBuffer();
            for (int i = 0; i < params.length; i++) {
                Class clazz = params[i];
                String type = clazz.getName();
                String paramName = toLowerFirstCase(clazz.getSimpleName());
                paramNames.append(type + " " + paramName);
                paramValues.append(paramName);
                paramClasses.append(clazz.getName() + ".class");
                if (i > 0 && i < params.length - 1) {
                    paramNames.append(",");
                    paramClasses.append(",");
                    paramValues.append(",");
                }
            }
            sb.append("public " + m.getReturnType().getName() + " " + m.getName() + "(" + paramNames + ") {" + ln);
            sb.append("try{" + ln);
            sb.append("Method m = " + interfaces[0].getName() + ".class.getMethod(\"" + m.getName() + "\",new Class[]{" + paramClasses + "});" + ln);
            sb.append((hasReturnValue(m.getReturnType()) ? "return " : "") + getCaseCode("this.invocationHandler.invoke(this,m,new Object[]{" + paramClasses + "})", m.getReturnType()) + ";" + ln);
            sb.append("}catch(Error ex) { }");
            sb.append("catch(Throwable e){" + ln);
            sb.append("throw new UndeclaredThrowableException(e);" + ln);
            sb.append("}");
            sb.append(getReturnEmptyCode(m.getReturnType()));
            sb.append("}");
        }
        sb.append("}" + ln);
        return sb.toString();
    }
    /**
     * 定義返回類型
     */
    private static Map<Class, Class> mappings = new HashMap<Class, Class>();
    /**
     * 初始化一些返回類型
     */
    static {
        mappings.put(int.class, Integer.class);
        mappings.put(Integer.class, Integer.class);
        mappings.put(double.class, Double.class);
        mappings.put(Double.class, Double.class);
    }
    private static String getReturnEmptyCode(Class<?> returnClass) {
        if (mappings.containsKey(returnClass)) {
            if (returnClass.equals(int.class) || returnClass.equals(Integer.class)) {
                return "return 0;";
            } else if (returnClass.equals(double.class) || returnClass.equals(Double.class)) {
                return "return 0.0;";
            } else {
                return "return 0;";
            }
        } else if (returnClass == void.class) {
            return "";
        } else {
            return "return null;";
        }
    }
    /**
     * 判斷返回值類型
     *
     * @param code
     * @param returnClass
     * @return
     */
    private static String getCaseCode(String code, Class<?> returnClass) {
        if (mappings.containsKey(returnClass)) {
            // ((java.lang.Double) this.invocationHandler.invoke(this, m, new Object[]{})).doubleValue();
            String re = "((" + mappings.get(returnClass).getName() + ")" + code + ")." + returnClass.getSimpleName().toLowerCase() + "Value()";
            return re;
        }
        return code;
    }
    /**
     * 判斷代理接口的方法的返回值是否為void
     *
     * @param clazz 方法的返回值類型
     * @return
     */
    private static boolean hasReturnValue(Class<?> clazz) {
        return clazz != void.class;
    }
    /**
     * 參數(shù)首字母小寫
     *
     * @param src
     * @return
     */
    private static String toLowerFirstCase(String src) {
        char[] chars = src.toCharArray();
        if (chars[0] >= 'A' && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }
    /**
     * 首字母大寫
     *
     * @param src
     * @return
     */
    private static String toUpperFirstCase(String src) {
        char[] chars = src.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] -= 32;
        }
        return String.valueOf(chars);
    }
}

使用自定義動(dòng)態(tài)代理類

創(chuàng)建接口

public interface IUser {
    void shopping();
    Double expenses();
}

創(chuàng)建被代理接口

public class User implements IUser {
    @Override
    public void shopping() {
        System.out.println("user shopping....");
    }
    @Override
    public Double expenses() {
        return 50.5;
    }
}

創(chuàng)建代理接口

public class UseProxy implements MyInvocationHandler {
    private Object target;
    public Object myJDKProxy(Object target){
        this.target = target;
        Class&lt;?&gt; clazz =  target.getClass();
        return MyProxy.newProxyInstance(new MyClassLoader(),clazz.getInterfaces(),this);
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理user,執(zhí)行shopping()開始...");
        Object result = method.invoke(this.target, args);
        System.out.println("代理user,執(zhí)行shopping()結(jié)束...");
        return result;
    }
}

客戶端調(diào)用

    public static void main(String[] args) {
        UseProxy useProxy = new UseProxy();
        IUser user = (IUser) useProxy.myJDKProxy(new User());
        user.shopping();
        System.out.println(user.expenses());
    }

執(zhí)行結(jié)果

代理user,執(zhí)行shopping()開始...
user shopping....
代理user,執(zhí)行shopping()結(jié)束...
--------------------------------
代理user,執(zhí)行shopping()開始...
代理user,執(zhí)行shopping()結(jié)束...
--------------------------------
50.5

生成源代碼

查看生產(chǎn)的Java文件源代碼

package cn.ybzy.demo.proxy.proxy;
import cn.ybzy.demo.proxy.client.IUser;
import java.lang.reflect.*;
public class $Proxy0 implements cn.ybzy.demo.proxy.client.IUser{
MyInvocationHandler invocationHandler;
public $Proxy0(MyInvocationHandler invocationHandler) { 
this.invocationHandler = invocationHandler;}
public java.lang.Double expenses() {
try{
Method m = cn.ybzy.demo.proxy.client.IUser.class.getMethod("expenses",new Class[]{});
return ((java.lang.Double)this.invocationHandler.invoke(this,m,new Object[]{})).doubleValue();
}catch(Error ex) { }catch(Throwable e){
throw new UndeclaredThrowableException(e);
}return 0.0;}public void shopping() {
try{
Method m = cn.ybzy.demo.proxy.client.IUser.class.getMethod("shopping",new Class[]{});
this.invocationHandler.invoke(this,m,new Object[]{});
}catch(Error ex) { }catch(Throwable e){
throw new UndeclaredThrowableException(e);
}}}

以上就是關(guān)于“JDK動(dòng)態(tài)代理如何實(shí)現(xiàn)”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

jdk
AI