今天在研究Webwork2&Struts2的时候仔细研究了一下Dynamic proxy。
Dynamic proxy在很多的时候都要用到 ,例如 Spring的AOP, Webwork&Struts2的Interceptor,EJB
proxy与dynamic proxy的区别
业务接口:
HelloWorld .java
java 代码
- public interface HelloWorld {
- void sayHelloWorld() ;
- }
业务接口实现:
HelloWorldImpl .java
java 代码
- public class HelloWorldImpl implements HelloWorld {
- public void sayHelloWorld() {
- System.out.println("Hello World!");
- }
- }
-
dynamic proxy方式的代理:
HelloWorldHandler .java
java 代码
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- public class HelloWorldHandler implements InvocationHandler {
-
- private Object objOriginal;
-
-
-
-
- public HelloWorldHandler(Object obj) {
- this.objOriginal = obj ;
- }
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- Object result ;
-
- doBefore();
-
- result = method.invoke(this.objOriginal ,args);
-
- doAfter();
- return result ;
- }
- private void doBefore() {
- System.out.println("before method invoke!");
- }
- private void doAfter() {
- System.out.println("after method invoke!");
- }
- }
proxy方式的代理
HelloWorldProxy .java
java 代码
- public class HelloWorldProxy implements HelloWorld {
-
- private HelloWorldImpl objImpl
-
-
-
-
- public HelloWorldHandlerHelloWorldImpl objImpl{
- this.objImpl= objImpl;
- }
- public void sayHelloWorld() {
- System.out.println("In the Proxy Class!");
- objImpl.sayHelloWorld();
- System.out.println("In the Proxy Class!");
- }
- }
dynamic proxy方式测试代码:
Test .java
java 代码
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Proxy;
- public class Test {
- public static void main(String[] args) {
- HelloWorld hw = new HelloWorldImpl();
- InvocationHandler handler = new HelloWorldHandler(hw);
- HelloWorld proxy = (HelloWorld) Proxy.newProxyInstance(
- hw.getClass().getClassLoader(),
- hw.getClass().getInterfaces(),
- handler);
- proxy.sayHelloWorld();
- }
- }
Notice:newProxyInstance传递的是一个接口对象。否则会报错