package test;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.Random;
public class ProxyTest {
public static void main(String[] args) {
Object[] elements = new Object[100];
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);
elements[i] = proxy;
}
Integer key = new Random().nextInt(elements.length + 1) + 1;
int result = Arrays.binarySearch(elements, key);
if (result >= 0) {
System.out.print(elements[result]);
}
}
}
class TraceHandler implements InvocationHandler{
private Object target;
public TraceHandler(Object t){
this.target = t;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.print(target);
System.out.print("." + method.getName() + "(");
if (args != null) {
for (int j = 0; j < args.length; j++) {
System.out.print(args[j]);
if (j < args.length - 1) {
System.out.print(", ");
}
}
}
System.out.println(")");
return method.invoke(target, args);
}
}
Integer封装类完整形式:public final class Integer extends Number implements Comparable<Integer> {... }实现了Comparable<Integer>接口。method.invoke(target, args)找到具体的实现类。
自己编码部分:
package test;
import java.lang.reflect.*;
public class ProxyAPITest {
public static void main(String[] args) {
final ProxyAPI proxyA = new ProxyAPIImpl();
Object elements = new Object();
InvocationHandler handler = new TraceAPIHandler(elements);
Object proxy = Proxy.newProxyInstance(null,
new Class[] { ProxyAPI.class }, handler);
ProxyAPI proxyAPI = (ProxyAPI)elements;
proxyAPI.hello();
}
}
class TraceAPIHandler implements InvocationHandler{
private Object target;
public TraceAPIHandler(Object t){
this.target = t;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.print(target);
System.out.print("." + method.getName() + "(");
if (args != null) {
for (int j = 0; j < args.length; j++) {
System.out.print(args[j]);
if (j < args.length - 1) {
System.out.print(", ");
}
}
}
System.out.println(")");
return method.invoke(target, args);
}
}
package test;
public interface ProxyAPI {
public void hello();
}
package test;
public class ProxyAPIImpl implements ProxyAPI {
public void hello(){
System.out.println("你好,美好的世界,欢迎来到代理的世界!");
}
}
结果:运行错误,报“interface test.ProxyAPI is not visible from class loader”,还是不懂,看了一篇介绍说是,代理相当于代理人这个概念,有点不信,还待继续调查。