java动态代理解析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012417380/article/details/79928190

一、Java创建动态代理对象步骤

java动态代理创建对象的过程为如下步骤:
1. 通过实现InvocationHandler接口创建自己的调用处理器。

调用处理器实现InvocationHandler接口的invoke方法。代理类的方法调用会将代理对象、调用方法的Method对象、方法的参数数组传递给调用处理器对象的 invoke方法,我们需要在invoke方法中,将方法调用委托给被代理对象执行。所以调用处理器内部通常包含指向委托类实例的引用,用于真正执行分派转发过来的方法调用。

public class DynamicProxyHandler implements InvocationHandler {

    private Object proxied;

    public DynamicProxyHandler(Object proxied) {
        super();
        this.proxied = proxied;
    }

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

      .......

        return method.invoke(proxied,args );
    }

}

InvocationHandler  handler = new DynamicProxyHandler(..); 

2.通过为 Proxy 类指定 ClassLoader 对象和一组 interface 来创建动态代理类;

// 通过 Proxy 为包括 Interface 接口在内的一组接口动态创建代理类的类对象
Class clazz = Proxy.getProxyClass(classLoader, new Class[] { Interface.class, ... }); 

3.通过反射机制获得动态代理类的构造函数,其唯一参数类型是调用处理器接口类型;

// 通过反射从生成的类对象获得构造函数对象
Constructor constructor = clazz.getConstructor(new Class[] { InvocationHandler.class });

4.通过构造函数创建动态代理类实例,构造时调用处理器对象作为参数被传入。

// 通过构造函数对象创建动态代理类实例
Interface Proxy = (Interface)constructor.newInstance(new Object[] { handler });

Proxy类newProxyInstance方法直接创建代理对象

Proxy类的newProxyInstance静态方法封装了上面2-4流程:

InvocationHandler  handler = new DynamicProxyHandler(..); 

// 通过 Proxy 直接创建动态代理类实例
Interface proxy = (Interface)Proxy.newProxyInstance( classLoader, 
     new Class[] { Interface.class }, 
     handler );

二、使用示例

Proxy类可以对一组接口进行代理。被代理类和代理类实现了相同的接口。这里以一个公共接口为例

//Interface.java

public interface Interface {
     public  void doSomething();
     public  void somethingElse(String arg);
}

被代理类定义如下:

//RealObject.java

public class RealObject implements Interface {

    @Override
    public void doSomething() {
        System.out.println("doSomething");

    }

    @Override
    public void somethingElse(String arg) {
         System.out.println("somethingElse "+arg);
    }

}

调用处理器接口实现如下,方法调用前打印方法名和方法参数:

public class DynamicProxyHandler implements InvocationHandler {

    private Object proxied;

    public DynamicProxyHandler(Object proxied) {
        super();
        this.proxied = proxied;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("**** proxy: "+proxy.getClass()+" ,method: "+method.getName()+" ,args: "+args);
        if(args!=null)
            for(Object arg: args){
                System.out.println("  "+arg);
            }
        return method.invoke(proxied,args );
    }

}

动态代理实现如下:

public class SimpleDynamicProxy {

    public static void consumer(Interface iface){
        iface.doSomething();
        iface.somethingElse("bonobo");
    }
    public static void main(String[] args) {
        RealObject real = new RealObject();
        consumer(real);
        Interface proxy = (Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[]{Interface.class}, new DynamicProxyHandler(real));
        consumer(proxy);
    }

}

执行后输出:

doSomething
somethingElse bonobo
**** proxy: class com.sun.proxy.$Proxy0 ,method: doSomething ,args: null
doSomething
**** proxy: class com.sun.proxy.$Proxy0 ,method: somethingElse ,args: [Ljava.lang.Object;@6bc7c054
  bonobo
somethingElse bonobo

可以看到打印出了被调用的方法名和方法参数

三、动态代理相关类源码解析

1.java.lang.reflect.InvocationHandler

InvocationHandler为调用处理接口。每个生成的代理对象都拥有一个实现InvocationHandler接口的调用处理类。当生成的代理对象调用自己的方法时,会把自身引用和调用的方法对象传递给该方法集中处理。


@procy   代理对象的实例
@method  被调用的方法对象
@args    被调用方法的实际参数值
public interface InvocationHandler {
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;
}

2. java.lang.reflect.Proxy类

Proxy 类提供静态方法用来创建一组接口的动态代理类和动态代理类的实例。它是这些静态方法创建的动态代理类的父类。

Proxy的主要静态成员变量

  //代理类构造器参数类型
 private static final Class<?>[]constructorParams ={ InvocationHandler.class };

 //代理对象的调用处理器对象的引用
  protected InvocationHandler h;

 // 映射表:用于维护类装载器对象到其对应的代理类缓存   ClassLoder-Interfaces-ProxyClass   
 private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

Proxy的构造方法

//禁止外部调用,内部也从未调用
private Proxy() {
    }
// 由于 Proxy 内部从不直接调用构造函数,所以 protected 意味着只有子类可以调用   
protected Proxy(InvocationHandler h) {
        Objects.requireNonNull(h);
        this.h = h;
    }  

Proxy的静态方法

// 方法 1: 该方法用于获取指定代理对象所关联的调用处理器
public static InvocationHandler getInvocationHandler(Object proxy) 

// 方法 2:该方法用于获取关联于指定类装载器和一组接口的动态代理类的类对象
public static Class<?> getProxyClass(ClassLoader loader, 
Class<?>... interfaces)

// 方法 3:该方法用于判断指定类对象是否是一个动态代理类
public static boolean isProxyClass(Class<?> cl) 

// 方法 4:该方法用于为指定类装载器、一组接口及调用处理器生成动态代理类实例
public static Object newProxyInstance(ClassLoader loader,
 Class<?>[] interfaces,InvocationHandler h)

Proxy的生成过程

1.newProxyInstance方法

newProxyInstance方法调用getProxyClass0方法获取代理类

    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        //检查InvocationHandler是否为null,如果为null直接抛异常
        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);
        }
    }

2.getProxyClass0方法

.getProxyClass0方法通过映射表缓存获取代理类。没有的话通过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);
    }

3.静态内部类ProxyClassFactory的apply方法

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());
            }
        }
    }

可以看到在apply方法中,下面这行代码生成了内部类

/*
 * Generate the specified proxy class.
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);

4.ProxyGenerator类

ProxyGenerator类源码:http://www.docjar.com/html/api/sun/misc/ProxyGenerator.java.html

ProxyGenerater类源码解析:https://www.cnblogs.com/liuyun1995/p/8144706.html

Eclipse导入该ProxyGenerater:导入某些特殊Jar包中的类

自己实现生成代理类的工具类

该工具类对指定接口生成代理类

导入某些特殊Jar包中的类

package com.lengyu.proxy;

import java.io.FileOutputStream;
import java.io.IOException;

import sun.misc.ProxyGenerator;

public class ProxyUtils {
    /*
    * Save proxy class to path
    * 
    * @param path path to save proxy class
    * @param proxyClassName name of proxy class
    * @param interfaces interfaces of proxy class
    * @return
    */
   public static boolean saveProxyClass(String path, String proxyClassName, Class[] interfaces) {
       if (proxyClassName == null || path == null) {
           return false;
       }

       // get byte of proxy class
       byte[] classFile = ProxyGenerator.generateProxyClass(proxyClassName, interfaces);
       FileOutputStream out = null;
       try {
           out = new FileOutputStream(path);
           out.write(classFile);
           out.flush();
           return true;
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           try {
               out.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return false;
}
}

在main方法中调用该类,生成代理类的.calss文件

public class SimpleDynamicProxy {

    public static void consumer(Interface iface){
        iface.doSomething();
        iface.somethingElse("bonobo");
    }
    public static void main(String[] args) {
        RealObject real = new RealObject();
        consumer(real);
        Interface proxy = (Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[]{Interface.class}, new DynamicProxyHandler(real));
        consumer(proxy);
        ProxyUtils.saveProxyClass("K://ProxySubject.class","ProxySubject",new Class[]{Interface.class});
        //createProxyClassFile() ;
    }
    public static void createProxyClassFile()   
      {   
        String name = "ProxySubject";   
        byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Interface.class } );   
        try  
        {   
          FileOutputStream out = new FileOutputStream( name + ".class" );   
          out.write( data );   
          out.close();   
        }   
        catch( Exception e )   
        {   
          e.printStackTrace();   
        }   
      }   

}

用反汇编生成后的ProxySubject.class文件,可以看到Proxy的java代吗

import com.lengyu.proxy.Interface;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class ProxySubject
  extends Proxy
  implements Interface
{
  private static Method m1;
  private static Method m3;
  private static Method m2;
  private static Method m4;
  private static Method m0;

  public ProxySubject(InvocationHandler paramInvocationHandler)
  {
    super(paramInvocationHandler);
  }

  public final boolean equals(Object paramObject)
  {
    try
    {
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  public final void doSomething()
  {
    try
    {
      this.h.invoke(this, m3, null);
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  public final String toString()
  {
    try
    {
      return (String)this.h.invoke(this, m2, null);
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  public final void somethingElse(String paramString)
  {
    try
    {
      this.h.invoke(this, m4, new Object[] { paramString });
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  public final int hashCode()
  {
    try
    {
      return ((Integer)this.h.invoke(this, m0, null)).intValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

  static
  {
    try
    {
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      m3 = Class.forName("com.lengyu.proxy.Interface").getMethod("doSomething", new Class[0]);
      m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
      m4 = Class.forName("com.lengyu.proxy.Interface").getMethod("somethingElse", new Class[] { Class.forName("java.lang.String") });
      m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
      return;
    }
    catch (NoSuchMethodException localNoSuchMethodException)
    {
      throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
    }
    catch (ClassNotFoundException localClassNotFoundException)
    {
      throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
    }
  }
}

项目附件:https://download.csdn.net/download/u012417380/10346419

参考文章:

彻底理解JAVA动态代理

Java动态代理

java动态代理原理及解析

猜你喜欢

转载自blog.csdn.net/u012417380/article/details/79928190
今日推荐