当然我在扯淡

JDK动态代理

最近复习了一下JDK自带的动态代理,在Java技术中,和动态代理连接最紧密的就是Spring中的AOP,所谓的面向切面技术。

静态代理

代理模式

根据此UML类图可以写出如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
interface Subject{  //UML图中的Subject
void sayHelloWorld();
}

class RealSubject implements Subject{ //UML图中RealSubject
@Override
public void sayHelloWorld(){
System.out.println("HelloWorld");
}
}

class Proxy implements Subject{ //UML图中的Proxy
private Subject helloWorld;
public Proxy(Subject helloWorld) {
this.helloWorld = helloWorld;
}

@Override
public void sayHello(){
System.out.println("Proxy start");
helloWorld.sayHelloWorld();
System.out.println("Proxy end");
}
}

public class Main{ //客户端
public static void main(){
Subject helloWorld = new Subject();
Proxy proxy = new Proxy(helloWorld);
proxy.sayHello();
}
}

代理模式的作用就在于动态的给类添加功能。
现在假如有另一个类和接口,同样要实现在方法调用前打印start,方法结束后打印end,只能添加如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
interface SubjectT{
void sayHelloWorldT();
}

class RealSubjectT implements SubjectT{
@Override
public void sayHelloT(){
System.out.println("HelloWorldT");
}
}

class ProxyT implements SubjectT{
private SubjectT helloWorld;
Public Proxy(SubjectT helloWorld) {
this.helloWorld = helloWorld;
}

@Override
public void sayHello(){
System.out.println("Proxy start");
helloWorld.sayHelloWorldT();
System.out.println("Proxy end");
}
}
//客户端代码同理

所以若要给另一个接口添加相同的功能,需要程序员取另写实现类ProxyT,动态代理就是为了解决这个问题。

JDK动态代理

先来看一下代码,注意观察和静态代理方法的异同.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.lang.reflect.*;
interface Subject{ //同静态代理
void sayHelloWorld();
}
class RealSubject implements Subject{ //同静态代理
@Override
public void sayHelloWorld(){
System.out.println("HelloWorld");
}
}
interface SubjectT{
void sayHelloWorldT();
}
class RealSubjectT implements SubjectT{
@Override
public void sayHelloWorldT(){
System.out.println("HelloWorldT");
}
}

class InvokeProxy implements InvocationHandler{ //比较和Proxy的异处,两类不可类比
private Object object;
public InvokeProxy(Object object){
this.object = object;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
System.out.println("Proxy start");
return method.invoke(object, args);
}
}

public class Main{
public static void main(String[] args) {
Subject realSubject = new RealSubject();
InvokeProxy invokeProxy = new InvokeProxy(realSubject);
Subject proxy = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[] {Subject.class}, invokeProxy);//此处proxy对比静态代理类中的proxy
proxy.sayHelloWorld();


SubjectT realSubjectT = new RealSubjectT();
InvokeProxy invokeProxyT = new InvokeProxy(realSubjectT);
SubjectT proxyT = (SubjectT)Proxy.newProxyInstance(SubjectT.class.getClassLoader(), new Class[] {SubjectT.class}, invokeProxyT);//proxyT 对比 proxyT
proxyT.sayHelloWorldT();
}
}

这样只需要写一个InvokeProxy来生成代理类,大大减少了程序猿的工作量。

原理

来看除了客户端之外的三个类, Subject, RealSubject, InvokeProxy,发现Subject和RealSubject同静态代理的代理,所以重点来看InvokeProxy和Main类。
Main类中有一行注释,生成的proxy可以对应静态代理中的proxy类,所以用如下方法将此类名打印出来,

1
2
3
4
5
6
7
8
9
public class Main{
public static void main(String[] args) {
Subject realSubject = new RealSubject();
InvokeProxy invokeProxy = new InvokeProxy(realSubject);
Subject proxy = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[] {Subject.class}, invokeProxy);//此处 Proxy对比静态代理类中的proxy
System.out.println(proxy.getClass().getName());
proxy.sayHelloWorld();
}
}

输出的是一个”$Proxy0”的类,很明显这个类并不是代码中写的,是Java自己生成的。
所以来分析一下Proxy.newProxyInstance()函数,去看Proxy源码,额由于源码过长,这里精简一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
public static Object newProxyInstance(ClassLoader classLoader, Class<?>[] interfaces, InvokcationHandler h){
//所有要实现的业务接口
final Class<?> intfs = interfaces.clone();

//寻找(从缓存中)或者生成代理类
Class<?> cl = getProxy(loader, intfs);

//通过Class获取Consturctor
Constructor<?> cons = cl.getConstructor(constructorParams);

//通过Constructor返回代理类
return cons.newInstance(new Objcer[] {h});
}

下面来看一下生成字节码文件的代码

1
2
3
4
5
6
7
8
9
//不是太想贴,精简一下吧,一方面是因为懒,另一方面是没看太懂
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces){
//如果缓存里面有,去缓存里面取,没有就生成,下面是生成的代码
String proxyName = proxyPkg + proxyClassNamePrefix + num;
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces);
//前面已经知道了类名叫"$Proxy0",所以下面直接得到这个class文件吧。

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.lang.reflect.*;
import java.io.*;
import sun.misc.ProxyGenerator;

public class GetProxy{
public static void main(String[] args) throws IOException{
Subject subject = new RealSubject();
InvokeProxy invokeProxy = new InvokeProxy(subject);
Subject proxy = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[] {Subject.class}, invokeProxy);

byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class[] {Subject.class});

File file = new File("/home/cat/Desktop/$Proxy0.class");
FileOutputStream output = new FileOutputStream(file);
output.write(bytes);
output.flush();
}
}

得到$Proxy0类之后,反编译看一下(什么,你问我怎么反编译,拖到IDEA里就可以了),贴代码了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
public final class $Proxy0
extends Proxy
implements Subject
{
private static Method m1;
private static Method m2;
private static Method m3;
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 void sayHelloWorld()
{
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()
{
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("Subject").getMethod("sayHelloWorld", 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());
}
}
}

重点看SayHelloWorld方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
m3 = Class.forName("Subject").getMethod("sayHelloWorld", new Class[0]);
public final void sayHelloWorld()
{
try
{
this.h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}

可知调用了InvokeProxy.invoke($Proxy0, m3, null),回到InvokeProxy类。