[编织消息框架][JAVA核心技术]jdk动态代理

时间:2023-08-13 16:07:08

需要用到的工具  jdk : javac javap

class 反编译 :JD-GUI http://jd.benow.ca/

先来看下jdk动态代理跟native性能比较

 package com.eyu.onequeue;

 import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; public class TestProxy {
public interface UserService {
public String getName(int id); public Integer getAge(int id);
} public static class UserServiceImpl implements UserService { @Override
public String getName(int id) {
return "name : " + id;
} @Override
public Integer getAge(int id) {
return id;
}
}; public static void main(String[] args) {
testNative();
testJdk();
} public static void testJdk() {
UserService impTarget = new UserServiceImpl();
// 代理处理逻辑
InvocationHandler handler = new InvocationHandler() { @Override
public Object invoke(Object target, Method method, Object[] args) throws Throwable {
return method.invoke(impTarget, args);
}
};
// Proxy.newProxyInstance(ClassLoader/**ClassLoader 没有特别处理 拿默认即可 **/,
// Class<?>[]/**代理接口类**/, InvocationHandler /**代理处理逻辑**/)
UserService proxy = (UserService) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[] { UserService.class }, handler); run("jdk", proxy);
} public static void testNative() {
UserService impTarget = new UserServiceImpl();
run("native", impTarget);
} private static void run(String tag, UserService impTarget) {
int c = 15;
System.out.println();
while (c-- > 0) {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
impTarget.getName(11);
}
long end = System.currentTimeMillis();
System.out.print(tag + ": " + (end - start) + " ");
}
}
}

运行结果:

native: 175 native: 182 native: 126 native: 172 native: 126 native: 127 native: 127 native: 126 native: 127 native: 126 native: 126 native: 128 native: 126 native: 127 native: 126
jdk: 214 jdk: 170 jdk: 169 jdk: 169 jdk: 170 jdk: 170 jdk: 170 jdk: 170 jdk: 170 jdk: 172 jdk: 169 jdk: 172 jdk: 169 jdk: 171 jdk: 169

先运行预热,看出执行五次之后比较稳定

jdk动态代理使用非常简单,使用Proxy.newProxyInstance 静态方法即可

接下来我们看下class指令

javac -encoding UTF-8 -d . TestProxy.java

javap -v com\eyu\onequeue\TestProxy.class > s.txt

其中

// Method java/lang/reflect/Proxy.newProxyInstance:(Ljava/lang/ClassLoader;[Ljava/lang/Class;Ljava/lang/reflect/InvocationHandler;)Ljava/lang/Object;

没有详细看到代理类指令

运行时生成的动态代理对象是可以导出到文件的,方法有两种

  1. 在代码中加入System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
  2. 在运行时加入jvm 参数 -Dsun.misc.ProxyGenerator.saveGeneratedFiles=true

我们在main方法加一行System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); 然后执行一下

  public static void main(String[] args) {
System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
//省略
}

这时在包下会多出$Proxy0.class文件

[编织消息框架][JAVA核心技术]jdk动态代理

proxy0.class用jd-gui打开

 package com.sun.proxy;

 import com.eyu.onequeue.TestProxy.UserService;
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 TestProxy.UserService
{
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m4;
private static Method m0; public $Proxy0(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 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 String getName(int paramInt)
{
try
{
return (String)this.h.invoke(this, m3, new Object[] { Integer.valueOf(paramInt) });
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
} public final Integer getAge(int paramInt)
{
try
{
return (Integer)this.h.invoke(this, m4, new Object[] { Integer.valueOf(paramInt) });
}
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") });
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m3 = Class.forName("com.eyu.onequeue.TestProxy$UserService").getMethod("getName", new Class[] { Integer.TYPE });
m4 = Class.forName("com.eyu.onequeue.TestProxy$UserService").getMethod("getAge", new Class[] { Integer.TYPE });
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());
}
}
}

proxy0

proxy0分析分两部份

1.在内存动态生成代理类 以$proxy 开头

$Proxy0 extends Proxy implements XXXXProxy.UserService

并初始化InvocationHandler 同绑定 Method

 public $Proxy0(InvocationHandler paramInvocationHandler)
{
  super(paramInvocationHandler);
} 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.eyu.onequeue.TestProxy$UserService").getMethod("getName", new Class[] { Integer.TYPE });
  m4 = Class.forName("com.eyu.onequeue.TestProxy$UserService").getMethod("getAge", new Class[] { Integer.TYPE });
  m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
  return;
}
.....
}

第二部分:代理原对象所有方法实现调用InvocationHandler 类的 Object invoke(Object target, Method method, Object[] args) throws Throwable 方法 再通过method反射invoke

public final String getName(int paramInt)
{
try
{
return (String)this.h.invoke(this, m3, new Object[] { Integer.valueOf(paramInt) });
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}

我们通过生成指令 E:\java\findme\com\sun\proxy>javap -v $Proxy0.class > d.txt

来查看代理过的getName方法共多少条指令

  public final java.lang.String getName(int) throws ;
descriptor: (I)Ljava/lang/String;
flags: ACC_PUBLIC, ACC_FINAL
Code:
stack=10, locals=3, args_size=2
0: aload_0
1: getfield #16 // Field java/lang/reflect/Proxy.h:Ljava/lang/reflect/InvocationHandler;
4: aload_0
5: getstatic #57 // Field m3:Ljava/lang/reflect/Method;
8: iconst_1
9: anewarray #22 // class java/lang/Object
12: dup
13: iconst_0
14: iload_1
15: invokestatic #63 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
18: aastore
19: invokeinterface #28, 4 // InterfaceMethod java/lang/reflect/InvocationHandler.invoke:(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;
24: checkcast #52 // class java/lang/String
27: areturn
28: athrow
29: astore_2
30: new #42 // class java/lang/reflect/UndeclaredThrowableException
33: dup
34: aload_2
35: invokespecial #45 // Method java/lang/reflect/UndeclaredThrowableException."<init>":(Ljava/lang/Throwable;)V
38: athrow
Exception table:
from to target type
0 28 28 Class java/lang/Error
0 28 28 Class java/lang/RuntimeException
0 28 29 Class java/lang/Throwable
Exceptions:
throws

如果不出错,到 27:areturn  至少要执行到13条指令 java8对动态代理有优化过

结论是:jdk动态代理比原生调用只慢几十毫秒,这点可以忽略不计