1. Static proxy class
1.1 Define the interface
public interface A{
void a(String str);
}
1.2 Implement the interface
public class B implements A{
@Override
public void a(String str) {
System.out.println(str);
}
}
1.3 Create a static proxy
public class Proxy {
private B b;
public Proxy(){
}
public Proxy(B b) {
this.b= b;
}
public void a(String str){
pre();
b.a(str);
after();
}
public void pre(){
System.out.println("前执行");
}
public void contract(){
System.out.println("后执行");
}
}
1.4 Testing
public class Test{
public static void main(String[] args) {
B b= new B();
Proxy proxy = new Proxy(b);
proxy.a("我是传入参数");
}
}
2. Dynamic proxy
2.1 Universal agent class
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 万能代理类
* @author administratoirs
*/
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的类
private Object target;
public void setObject(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
//创建代理实例(通过反射获取参数):类加载器、被代理的接口、InvocationHandler接口
Object obj = Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
return obj;
}
//执行代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
pre();
Object res = method.invoke(target, args);
after();
return res;
}
public void pre() {
System.out.println("执行前");
}
public void after(){
System.out.println("执行后");
}
}
2.2 Testing
public class Client {
public static void main(String[] args) {
//要被代理的类
B b = new B();
//代理角色:可通过ProxyInvocationHandler创建出来,可以通过这个类动态创建
ProxyInvocationHandler handler = new ProxyInvocationHandler();
//设置代理的真实角色
handler.setObject(b);
//getProxy动态生成代理类
B proxy =(B) handler.getProxy();
//就是执行invoke
proxy.a("我是传入参数");
}
}