public interface B {
public void refA();
}
public class A implements B{
public void refA() {
System.out.println("This A");
}
}
public class C implements B{
@Override
public void refA() {
System.out.println("This C");
}
}
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MapperProxy implements InvocationHandler, Serializable {
private Object obj;
<T> MapperProxy(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(" before calling " + method);
System.out.println(method.getDeclaringClass());
System.out.println(Object.class);
method.invoke(obj, args);
System.out.println(" after calling " + method);
return null;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
try {
ProxyTest p = new ProxyTest();
/* B aa = p.proxyClass((Class<T>) Class.forName("com.navinfo.sys.test.A")
.newInstance().getClass());*/
B aa = p.proxyClass(B.class);
aa.refA();
} catch (Exception e) {
e.printStackTrace();
}
}
public <T> T proxyClass(Class<T> mapperInterface) {
// java 动态代理
ClassLoader classLoader = mapperInterface.getClassLoader();
Class<?>[] interfaces = new Class[] { mapperInterface };
for (int i = 0; i < interfaces.length; i++) {
System.out.println("||" + interfaces[i]);
}
B a = new C();
InvocationHandler proxy = new MapperProxy(a);
return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
}
}
java动态代理类位于java.lang.reflect包下,一般主要涉及到以下两个类:
- Interface InvocationHandler:该接口中仅定义了一个方法Object:invoke(Object obj,Method method, Object[] args)。在实际使用时,第一个参数obj一般是指代理 类,method是被代理的方法,如上例中的request(),args为该方法的参数数组。 这个抽 象方法在代理类中动态实现。
- Proxy:该类即为动态代理类,作用类似于上例中的ProxySubject。
- Protected Proxy(InvocationHandler h):构造函数,估计用于给内部的h赋值。
- Static Class getProxyClass (ClassLoader loader, Class[] interfaces):获得一个 代理类,其中loader是类装载器,interfaces是真实类所拥有的全部接口的数组。
- Static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h):返回代理类的一个实例,返回后的代理类可以当作被代理类使用 (可使用被代理类的在Subject接口中声明过的方法)。
在使用动态代理类时,我们必须实现InvocationHandler接口,