1. 程式人生 > >搞懂Java動態代理

搞懂Java動態代理

代理

  代理模式的定義:為其他物件提供一種代理以控制對這個物件的訪問。即代理物件B控制真實物件A的訪問,那為什麼不直接使用真實物件?有時候真實物件不便直接使用或者不能直接使用,需要對真實物件進行增強,但又不能改變真實物件屬性(開閉原則),這時就需要用到代理類。

  代理類主要負責為委託了(真實物件)預處理訊息、過濾訊息、傳遞訊息給委託類,代理類不現實具體服務,而是利用委託類來完成服務,並將執行結果封裝處理。有兩種方式的代理:

  • 靜態代理:程式設計師將代理類預先建立好。
  • 動態代理:代理類在程式執行過程中動態建立。

  一個典型的代理模式通常有三個角色,這裡稱之為代理三要素:共同介面、真實物件、代理物件。

靜態代理

共同介面:

public interface Sell {

    void add(String name);

    void sell(String name);
}

真實物件:

public class Seller implements Sell {
    @Override
    public void add(String name) {
        System.out.println("add product:" + name);
    }

    @Override
    public void sell(String name) {
        System.out.println("sell product:"
+ name); } }

代理物件:

public class ProxySeller implements Sell {

    private Sell sell;

    public ProxySeller(Sell sell){
        this.sell = sell;
    }

    @Override
    public void add(String name) {
        sell.add(name);
    }

    @Override
    public void sell(String name) {
        sell.sell(name);
    }
}

代理物件呼叫,真實物件Seller被傳遞給了代理物件ProxySeller,代理物件在執行具體方法時通過所持用的真實物件完成呼叫。

 public static void main(String[] args) {
        System.out.println("Hello World!");

        Sell sell = new ProxySeller(new Seller());
        sell.add("Apple");
        sell.sell("Apple");
 }

這裡寫圖片描述

在處理部分物件增強功能時,靜態代理還是較合適,因為其直接落腳具體物件具體方法。但有時候面對不同物件、不同方法的代理場景時,這種代理模式就不是很靈活:

  • 方式一:針對不同物件,分別建立一個代理類。
  • 方式二:僅用一個代理類,實現n個不同的介面,最終分類呼叫。

這裡寫圖片描述

在方案一中,會重複建立邏輯相同僅引用物件不同的代理類;方案二中會造成一個代理類的無線膨脹,最終難以控制及維護。接下來,引出動態代理…

動態代理

共同介面、真實物件不變,我們構建一個代理物件呼叫處理程式InvocationHandler。

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class SellerInvocationHandler implements InvocationHandler {

    private Object delegate;

    public SellerInvocationHandler(Object delegate){
        this.delegate = delegate;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("Befor");
        method.invoke(delegate,args);
        System.out.println("After");
        return null;
    }
}

執行動態代理:

 public static void main(String[] args) {
        System.out.println("Hello World!");

        Sell delegate = new Seller();

        InvocationHandler handler = new SellerInvocationHandler(delegate);

        Sell proxy = (Sell)Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
                                            delegate.getClass().getInterfaces(),
                                            handler);
        proxy.add("Apple");
        proxy.sell("Apple");
}

這裡寫圖片描述

通過Proxy類的靜態方法newProxyInstance返回一個介面的代理例項。針對不同的代理類,傳入相應的代理程式控制器InvocationHandler。如果新來一個委託類PrimaryStudent,如:

public interface Student {

    void buy(String name);

    void say(String name);
}

public class PrimaryStudent implements Student {
    @Override
    public void buy(String name) {
        System.out.println("Student Buy " + name);
    }

    @Override
    public void say(String name) {
        System.out.println("Student Say " + name);
    }
}

實現對這個類的動態代理過程如下:

 public static void main(String[] args) {
        System.out.println("Hello World!");

        Sell delegate = new Seller();
        Student student = new PrimaryStudent();
        InvocationHandler handler = new SellerInvocationHandler(delegate);
        InvocationHandler handler1 = new SellerInvocationHandler(student);

        Sell proxy = (Sell)Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
                                            delegate.getClass().getInterfaces(),
                                            handler);

        Student proxy1 = (Student)Proxy.newProxyInstance(student.getClass().getClassLoader(),
                                            student.getClass().getInterfaces(),
                                            handler1);

        proxy.add("Apple");
        proxy.sell("Apple");

        proxy1.say("Apple");
        proxy1.buy("Apple");
    }

這裡寫圖片描述

其實動態代理的基本要素仍然是:1、共同介面;2、真是物件;3代理物件(只不過此時的代理類是自動生成的)。Spring AOP就是動態代理的典型實現。

道理差不多明白了,接下來繼續瞭解動態代理底層的過程,及代理類如何生成的…

底層過程

newProxyInstance方法究竟是如何生成一個代理例項的,通過其原始碼展開說明:

@CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        Objects.requireNonNull(h);

        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         * Look up or generate the designated proxy class.
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{h});
        } catch (IllegalAccessException|InstantiationException e) {
            throw new InternalError(e.toString(), e);
        } catch (InvocationTargetException e) {
            Throwable t = e.getCause();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new InternalError(t.toString(), t);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString(), e);
        }
    }

整體流程:

  • 1、生成代理類Proxy的Class物件。
  • 2、如果Class作用域為私有,通過 setAccessible 支援訪問
  • 3、獲取Proxy Class建構函式,建立Proxy代理例項。

其中,利用getProxyClass0(loader, intfs)生成代理類Proxy的Class物件,其原始碼如下,其中有說明,如果指定介面的代理類已經存在與快取中,則不用新建立,直接從快取中取即可;如果快取中沒有指定代理物件,則通過ProxyClassFactory來建立一個代理物件。

/**
     * Generate a proxy class.  Must call the checkProxyAccess method
     * to perform permission checks before calling this.
     */
    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }

        // If the proxy class defined by the given loader implementing
        // the given interfaces exists, this will simply return the cached copy;
        // otherwise, it will create the proxy class via the ProxyClassFactory
        return proxyClassCache.get(loader, interfaces);
    }

ProxyClassFactory內部類建立、定義代理類,返回給定ClassLoader 和interfaces的代理類。其中核心方法就是apply,

/**
     * A factory function that generates, defines and returns the proxy class given
     * the ClassLoader and array of interfaces.
     */
    private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names
        private static final String proxyClassNamePrefix = "$Proxy";

        // next number to use for generation of unique proxy class names
        private static final AtomicLong nextUniqueNumber = new AtomicLong();

        @Override
        public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
            for (Class<?> intf : interfaces) {
                /*
                 * Verify that the class loader resolves the name of this
                 * interface to the same Class object.
                 */
                Class<?> interfaceClass = null;
                try {
                    interfaceClass = Class.forName(intf.getName(), false, loader);
                } catch (ClassNotFoundException e) {
                }
                if (interfaceClass != intf) {
                    throw new IllegalArgumentException(
                        intf + " is not visible from class loader");
                }
                /*
                 * Verify that the Class object actually represents an
                 * interface.
                 */
                if (!interfaceClass.isInterface()) {
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                /*
                 * Verify that this interface is not a duplicate.
                 */
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }

            String proxyPkg = null;     // package to define proxy class in
            int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

            /*
             * Record the package of a non-public proxy interface so that the
             * proxy class will be defined in the same package.  Verify that
             * all non-public proxy interfaces are in the same package.
             */
            for (Class<?> intf : interfaces) {
                int flags = intf.getModifiers();
                if (!Modifier.isPublic(flags)) {
                    accessFlags = Modifier.FINAL;
                    String name = intf.getName();
                    int n = name.lastIndexOf('.');
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use com.sun.proxy package
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                /*
                 * A ClassFormatError here means that (barring bugs in the
                 * proxy class generation code) there was some other
                 * invalid aspect of the arguments supplied to the proxy
                 * class creation (such as virtual machine limitations
                 * exceeded).
                 */
                throw new IllegalArgumentException(e.toString());
            }
        }
    }

proxyClassFile是生產的代理類位元組碼,generateProxyClass是真正生成代理類class位元組碼的函式,進去ProxyGenerator類的靜態方法generateProxyClass。

public static byte[] generateProxyClass(final String name,  
                                           Class[] interfaces)  
   {  
       ProxyGenerator gen = new ProxyGenerator(name, interfaces);  
    // 這裡動態生成代理類的位元組碼,由於比較複雜就不進去看了  
       final byte[] classFile = gen.generateClassFile();  

    // 如果saveGeneratedFiles的值為true,則會把所生成的代理類的位元組碼儲存到硬碟上  
       if (saveGeneratedFiles) {  
           java.security.AccessController.doPrivileged(  
           new java.security.PrivilegedAction<Void>() {  
               public Void run() {  
                   try {  
                       FileOutputStream file =  
                           new FileOutputStream(dotToSlash(name) + ".class");  
                       file.write(classFile);  
                       file.close();  
                       return null;  
                   } catch (IOException e) {  
                       throw new InternalError(  
                           "I/O exception saving generated file: " + e);  
                   }  
               }  
           });  
       }  

    // 返回代理類的位元組碼  
       return classFile;  
   }  

位元組碼生成後,呼叫defineClass0來解析位元組碼,生成了Proxy的Class物件。在瞭解完代理類動態生成過程後,生產的代理類是怎樣的,誰來執行這個代理類。

ProxyGenerator.generateProxyClass函式中注意下面一點:

if(saveGeneratedFiles) {
    ...
    FileOutputStream file = new FileOutputStream(dotToSlash(name) + ".class");
    file.write(classFile);
    ...
 }

saveGeneratedFiles定義如下,其指代是否儲存生成的代理類class檔案,預設false不儲存。

private static final boolean saveGeneratedFiles = ((Boolean)AccessController.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"))).booleanValue();

但是為了加深理解,我們可以在main函式中修改此係統變數,main中定義了2個真實物件Sell及Student,接下來看看其生成的代理物件。

public static void main(String[] args) {

        System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        Sell delegate = new Seller();
        Student student = new PrimaryStudent();
        InvocationHandler handler = new SellerInvocationHandler(delegate);
        InvocationHandler handler1 = new SellerInvocationHandler(student);

        Sell proxy = (Sell)Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
                                            delegate.getClass().getInterfaces(),
                                            handler);

        Student proxy1 = (Student)Proxy.newProxyInstance(student.getClass().getClassLoader(),
                                            student.getClass().getInterfaces(),
                                            handler1);

        proxy.add("Apple");
        proxy.sell("Apple");

        proxy1.say("Apple");
        proxy1.buy("Apple");
    }

這裡寫圖片描述

如圖,生成了兩個名為 $Proxy0.class、$Proxy1.class的class檔案,利用idea的反編譯能力,開啟兩檔案,其內容如下:

package com.sun.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy implements Sell {
    private static Method m1;
    private static Method m2;
    private static Method m4;
    private static Method m3;
    private static Method m0;

    //這個是$Proxy0繼承Proxy並呼叫了父類的構造方法
    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return ((Boolean)super.h.invoke(this, m1, new Object[]{var1})).booleanValue();
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }
    //實現介面Sell的代理方法sell
    public final void sell(String var1) throws  {
        try {
            super.h.invoke(this, m4, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }
    //實現介面Sell的代理方法add
    public final void add(String var1) throws  {
        try {
            super.h.invoke(this, m3, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final int hashCode() throws  {
        try {
            return ((Integer)super.h.invoke(this, m0, (Object[])null)).intValue();
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m4 = Class.forName("Sell").getMethod("sell", Class.forName("java.lang.String"));
            m3 = Class.forName("Sell").getMethod("add", Class.forName("java.lang.String"));
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

$Proxy0繼承了Proxy類,實現了Sell介面,是Sell物件的代理類。生成的代理類呼叫委託類方法時,呼叫InvocationHandler的invoke方法。

這裡寫圖片描述

總結

其實,動態代理實現思路與靜態代理一樣,也是“共同介面、真實物件、代理物件”,只不過靜態代理的代理物件是程式設計師預先寫好的,而動態代理的代理物件是利用位元組碼手段動態生成代理物件的,減少了重複勞動,所以優秀的程式設計師可能也是一個“懶惰”的程式設計師。