动态代理
Last updated
Was this helpful?
Last updated
Was this helpful?
要理解动态代理首先要理解代理或者说代理模式。
代理模式非常简单,被代理类和代理类实现同一个接口,并且在代理类的中有被代理类的实例。
举一个实际的例子
[IWork.java]
public interface IWork {
void work();
}
[Actor.java]
public class Actor implements IWork {
@Override
public void work() {
System.out.println("Actor must act movie!'");
}
}
[Agent.java]
public class Agent implements IWork {
private Actor mActor;
public Agent(Actor actor) {
mActor = actor;
}
@Override
public void work() {
System.out.println("Agent receive job and money!'");
mActor.work();
}
}
[ProxyPattern.java]
public class ProxyPattern {
public static void main(String[] args) {
Agent agent = new Agent(new Actor());
agent.work();
}
}
代理模式明白了之后,动态代理其实就很简单了,Java中通过自带的特性,可以动态生成一个实例的的代理实例,在代理实例的回调方法中进行业务的处理。下面我们通过实际例子实现上面静态代理的功能。
[IWork.java]
public interface IWork {
void work();
}
[Actor.java]
public class Actor implements IWork {
@Override
public void work() {
System.out.println("Actor must act movie!'");
}
}
[DynamicProxyHandler.java]
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicProxyHandler implements InvocationHandler {
private Object target;
public DynamicProxyHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("work")) {
System.out.println("Agent receive job and money!'");
}
method.invoke(target, args);
return null;
}
public static void main(String[] args) {
Actor actor = new Actor();
DynamicProxyHandler dynamicProxyHandler = new DynamicProxyHandler(actor);
IWork worker = (IWork) Proxy.newProxyInstance(
IWork.class.getClassLoader(),
new Class[] {IWork.class},
dynamicProxyHandler);
worker.work();
}
}