以例子来说明动态代理:
package com.gym;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface A {
public void a(int a);
}
interface B {
public void b(int b);
}
class BImpl implements InvocationHandler {
private A a = new A() {
public void a(int a) {
System.out.println("-----a------" + a);
}
public String toString() {
return "A";
};
};
private B b = new B() {
public void b(int b) {
System.out.println("-----b------" + b);
}
public String toString() {
return "B";
};
};
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (method.getName().equals("a")) {
method.invoke(a, args);
} else if (method.getName().equals("b")) {
method.invoke(b, args);
}
/*if (method.getName().equals("toString")) {
return "*********toString*************";
}*/
System.out.println(proxy instanceof A);
System.out.println(proxy instanceof B);
//System.out.println(proxy); //此处会死循环 (1)
return null;
}
@Override
public String toString() {
return "SSSSSSSSSSSS";
}
}
/**
*
* @author xinchun.wang
*
* Object obj = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class[] { A.class, B.class },new BImpl());
* 注意:
* obj 和 BImpl 实例之间的关系:首先obj 拥有BImpl,
* obj 和 A,B 实例之间的关系:obj 是A也是B,一个动态的代理实现
* 对比(1) (2) obj 的 toString方法 和 proxy 的关系
*/
public class JDKProxy {
public static void main(String[] args) {
Object obj = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class[] { A.class, B.class },new BImpl());
A a = (A) obj;
a.a(1);
System.out.println(a);
B b = (B) obj;
b.b(10);
System.out.println(obj); //(2)
System.out.println(Proxy.getInvocationHandler(obj));
}
}