nicolas 111216
主要资料参考自《Spring Gossip》
1.动态代理
利用动态代理,可代理一个具体的对象。从而在具体对象工作时,进行切面上的操作处理。
简单来说,可以对一个对象的操作进行封装。
2.动态代理需实现的接口
动态代理必须实现此接口:java.lang.reflect.InvocationHandler
3.动态代理技术简介
利用Proxy.newProxyInstance()静态方法创建一个代理对象(必须传入所要代理的接口),然后可用代理对象进行工作。调用代理对象的被代理方法时,调用接口InvocationHandler的invoke()方法,invoke()方法得到被代理对象的方法名称与执行参数,然后执行method.invoke()进行真正执行。method.invoke()的传回对象是被代理方法的执行结果。
4.切面
利用动态代理可创建代理对象,将业务逻辑无关操作放在代理层处理。被代理对象只需关注核心的业务逻辑即可。而代理层不介入具体业务,成为通用的业务无关切面层。
典型的应用有日志、安全控制等。
5.示例
1)被代理接口
public interface IHello {
public void hello(String name);
}
2)被代理对象
public class HelloSpeaker implements IHello {
public void hello(String name) {
System.out.println("Hello, " + name);
}
}
3)动态代理对象
public class LogHandler implements InvocationHandler {
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object delegate;
public Object bind(Object delegate) {
this.delegate = delegate;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
delegate.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
log("method starts..." + method);
result = method.invoke(delegate, args);
logger.log(Level.INFO, "method ends..." + method);
} catch (Exception e) {
log(e.toString());
}
return result;
}
private void log(String message) {
logger.log(Level.INFO, message);
}
}
4)主类
public class DynamicProxyDemo {
public static void main(String[] args) {
LogHandler logHandler = new LogHandler();
IHello helloProxy = (IHello) logHandler.bind(new HelloSpeaker());
helloProxy.hello("Justin");
}
}