代理

创建代理对象

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
package proxy;

import java.lang.reflect.*;
import java.util.*;


public class ProxyTest
{
public static void main(String[] args)
{
Object[] elements = new Object[1000];


for (int i = 0; i < elements.length; i++)
{
Integer value = i + 1;
InvocationHandler handler = new TraceHandler(value);
Object proxy = Proxy.newProxyInstance(null, new Class[] { Comparable.class } , handler);//(ClassLoader,Class对象数组,InvocationHandler)
elements[i] = proxy;
}

// construct a random integer
Integer key = new Random().nextInt(elements.length) + 1;

// search for the key
int result = Arrays.binarySearch(elements, key);//会获取到elements中的Comparable接口,调用compareTo(),而在compareTo()中调用了代理对象的InvocationHandler的invoke()

// print match if found
if (result >= 0) System.out.println(elements[result]);
}
}

/**
* An invocation handler that prints out the method name and parameters, then
* invokes the original method
*/
class TraceHandler implements InvocationHandler
{
private Object target;

/**
* Constructs a TraceHandler
* @param t the implicit parameter of the method call
*/
public TraceHandler(Object t)
{
target = t;
}

public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
{
// print implicit argument
System.out.print(target);
// print method name
System.out.print("." + m.getName() + "(");
// print explicit arguments
if (args != null)
{
for (int i = 0; i < args.length; i++)
{
System.out.print(args[i]);
if (i < args.length - 1) System.out.print(", ");
}
}
System.out.println(")");

// invoke actual method
return m.invoke(target, args);
}
}

代理类通过提供一个invocation handler(其实现了InnovationHandler接口,该函数接口只有一个invoke(object proxy,Method method,Object[] args)),只要调用代理对象的方法,invocation handler的invoke()都会被调用。

代理类的特性

代理类是在程序运行过程中创建的,所有同参数构造出来的代理类只会得到同一个代理类。可通过getProxyClass()获得这个类。

文章目录
  1. 1. 创建代理对象
  2. 2. 代理类的特性
|