Java自带的动态代理

Java自带的动态代理

大家都知道,代理模式是23中设计模式中的一种,代理模式又分为动态代理和静态代理,今天主要介绍下动态代理。目前流行的动态代理,一种是JDK自带的动态代理,另外一种就是cglib动态代理。所为的代理就是构造一个新对象,实现对原有对象所有行为的支持,同时又可以支持新的功能,比如常见的AOP。

JDK动态代理
先上代码

[java]
package com.learn.core.proxy;

public interface Subject {

public void doSth();
}

[/java]
真实的对象
[java]
package com.learn.core.proxy;

public class RealSubject implements Subject {

@Override
public void doSth() {
System.out.println("call doSth()");
}

}

[/java]
调用处理器
[java]
package com.learn.core.proxy;

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

public class ProxyHandler implements InvocationHandler {

private Object proxied;

public ProxyHandler(Object proxied) {
this.proxied = proxied;
}

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("do something before call");
Object obj = method.invoke(proxied, args);
System.out.println("do something after call");
return obj;
}

}

[/java]

测试入口
[java]
package com.learn.core.proxy;

import java.io.FileOutputStream;
import java.lang.reflect.Proxy;
import sun.misc.ProxyGenerator;

public class DynamicProxy {

public static void main(String args[]) {
RealSubject real = new RealSubject();
Subject proxySubject = (Subject) Proxy.newProxyInstance(Subject.class.getClassLoader(),
new Class[] { Subject.class }, new ProxyHandler(real));

proxySubject.doSth();

// write proxySubject class binary data to file
createProxyClassFile();
}

public static void createProxyClassFile() {
String name = "ProxySubject";
byte[] data = ProxyGenerator.generateProxyClass(name, new Class[] { Subject.class });
try {
FileOutputStream out = new FileOutputStream(name + ".class");
out.write(data);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

[/java]

–输出
do something before call
call doSth()
do something after call

大家看了上边的实现和输出,应该很快就明白了动态代理的效果。一般JDK的动态代理就几个步骤

  • 通过实现InvocationHandler接口创建自己的调用处理器。 常见的处理方式是把真实的对象传给InvocationHandler,还有一个做法是:InvocationHandler是个内部类,可以直接调用父类的实例方法和成员变量
  • 通过构造函数创建代理类实例,此时需将调用处理器对象作为参数被传入
    Interface Proxy = (Interface)constructor.newInstance(new Object[] (handler))
  • 生成的ProxySubject继承Proxy类实现Subject接口,实现的Subject的方法实际调用处理器的invoke方法,而invoke方法利用反射调用的是被代理对象的的方法(Object result=method.invoke(proxied,args))

    那JDK自带的动态代理是如何做到的呢?
    所有的核心都在newInstance方法里,如下
    [java]
    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);
    }
    }
    [/java]

    目前JDK8里用的ProxyClassFactory,它负责生成代理类的字节码
    [java]
    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.
    */
    //上边都是验证,ProxyGenerator生成代理类的字节码才是核心。
    //sun.misc.ProxyGenerator 不是标准的java类库
    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());
    }
    }
    }
    [/java]

    我反编译了如何生成字节码
    [java]
    private byte[] generateClassFile()
    {
    addProxyMethod(hashCodeMethod, Object.class);
    addProxyMethod(equalsMethod, Object.class);
    addProxyMethod(toStringMethod, Object.class);
    Object localObject4;
    for (localObject4 : this.interfaces) {
    for (Method localMethod : ((Class)localObject4).getMethods()) {
    addProxyMethod(localMethod, (Class)localObject4);
    }
    }
    for (??? = this.proxyMethods.values().iterator(); ((Iterator)???).hasNext();)
    {
    localList = (List)((Iterator)???).next();
    checkReturnTypes(localList);
    }
    try
    {
    List localList;
    this.methods.add(generateConstructor());
    for (??? = this.proxyMethods.values().iterator(); ((Iterator)???).hasNext();)
    {
    localList = (List)((Iterator)???).next();
    for (localIterator = localList.iterator(); localIterator.hasNext();)
    {
    localObject4 = (ProxyMethod)localIterator.next();

    this.fields.add(new FieldInfo(((ProxyMethod)localObject4).methodFieldName, "Ljava/lang/reflect/Method;", 10));

    this.methods.add(((ProxyMethod)localObject4).generateMethod());
    }
    }
    Iterator localIterator;
    this.methods.add(generateStaticInitializer());
    }
    catch (IOException localIOException1)
    {
    throw new InternalError("unexpected I/O Exception", localIOException1);
    }
    if (this.methods.size() > 65535) {
    throw new IllegalArgumentException("method limit exceeded");
    }
    if (this.fields.size() > 65535) {
    throw new IllegalArgumentException("field limit exceeded");
    }
    this.cp.getClass(dotToSlash(this.className));
    this.cp.getClass("java/lang/reflect/Proxy");
    for (localObject4 : this.interfaces) {
    this.cp.getClass(dotToSlash(((Class)localObject4).getName()));
    }
    this.cp.setReadOnly();

    ??? = new ByteArrayOutputStream();
    DataOutputStream localDataOutputStream = new DataOutputStream((OutputStream)???);
    try
    {
    localDataOutputStream.writeInt(-889275714);

    localDataOutputStream.writeShort(0);

    localDataOutputStream.writeShort(49);

    this.cp.write(localDataOutputStream);

    localDataOutputStream.writeShort(this.accessFlags);

    localDataOutputStream.writeShort(this.cp.getClass(dotToSlash(this.className)));

    localDataOutputStream.writeShort(this.cp.getClass("java/lang/reflect/Proxy"));

    localDataOutputStream.writeShort(this.interfaces.length);
    for (Object localObject6 : this.interfaces) {
    localDataOutputStream.writeShort(this.cp.getClass(
    dotToSlash(localObject6.getName())));
    }
    localDataOutputStream.writeShort(this.fields.size());
    for (??? = this.fields.iterator(); ((Iterator)???).hasNext();)
    {
    localObject5 = (FieldInfo)((Iterator)???).next();
    ((FieldInfo)localObject5).write(localDataOutputStream);
    }
    Object localObject5;
    localDataOutputStream.writeShort(this.methods.size());
    for (??? = this.methods.iterator(); ((Iterator)???).hasNext();)
    {
    localObject5 = (MethodInfo)((Iterator)???).next();
    ((MethodInfo)localObject5).write(localDataOutputStream);
    }
    localDataOutputStream.writeShort(0);
    }
    catch (IOException localIOException2)
    {
    throw new InternalError("unexpected I/O Exception", localIOException2);
    }
    return ((ByteArrayOutputStream)???).toByteArray();
    }

    [/java]

    最后让大家看看一开始代理类的反编译代码
    [java]
    import com.learn.core.proxy.Subject;
    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 Subject
    {
    private static Method m1;
    private static Method m2;
    private static Method m3;
    private static Method m0;

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

    public final boolean equals(Object paramObject)
    throws
    {
    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 String toString()
    throws
    {
    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 doSth()
    throws
    {
    try
    {
    this.h.invoke(this, m3, null);
    return;
    }
    catch (Error|RuntimeException localError)
    {
    throw localError;
    }
    catch (Throwable localThrowable)
    {
    throw new UndeclaredThrowableException(localThrowable);
    }
    }

    public final int hashCode()
    throws
    {
    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") });
    m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
    m3 = Class.forName("com.learn.core.proxy.Subject").getMethod("doSth", new Class[0]);
    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());
    }
    }
    }

    [/java]

    总结:
    Java自带的动态代理其实就是Java帮我们生成一个代理对象,它实现了所有我们需要的接口,所有的调用都会进入InvocationHandler,在InvocationHandler里通过反射区调用真实对象的方法。Proxy确实一个很漂亮的设计,尤其在我们不能改已有代码的前提下实现对已有对象行为的修改,但是美中不足的就是所有的依赖都是接口。

    Java 动态代理机制分析及扩展

    发表评论

    您的电子邮箱地址不会被公开。