A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.
可见Java
的动态代理是基于Interface
的。Spring AOP 功能就是利用的Java
动态代理。
动态代理的用处:
- 记入log, 在方法调用的前后记入log
- 参数检查
- 可以改变方法的原始行为
实现动态代理的要点:
- 创建业务需要的Interface
- 创建实现InvocationHandler
的代理类,主要是实现invoke
方法
- 通过Proxy.newProxyInstance()生成一个实现Interface的代理类
一个例子:
package ttttt;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import javax.management.RuntimeErrorException;
interface SomeInterface {
public void doSomething();
}
class SomeImpl implements SomeInterface {
@Override
public void doSomething() {
System.out.println("I am working!");
}
}
class SomeProxy implements InvocationHandler {
private SomeInterface SomeImpl;
public SomeProxy(SomeInterface someImpl) {
super();
SomeImpl = someImpl;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("proxy class is " + proxy.getClass().getCanonicalName());
System.out.println("Do something before.");
Object object = method.invoke(SomeImpl, args);
System.out.println("do something after.");
return object;
}
}
public class ProxyTest {
public static void main(String[] args) {
SomeInterface proxy = (SomeInterface) Proxy.newProxyInstance(SomeInterface.class.getClassLoader(),
new Class[] { SomeInterface.class }, new SomeProxy(new SomeImpl()));
proxy.doSomething();
}
}
执行结果:
proxy class is ttttt.$Proxy0
Do something before.
I am working!
do something after.