要代理的接口类
package com.yzy.test.dynaproxy;
public interface IHelloWorldInterface {
public void sayHello(); //测试代理的方法
}
要代理的接口类的实现
package com.yzy.test.dynaproxy.impl;
import com.yzy.test.dynaproxy.IHelloWorldInterface;
public class HelloWorldImpl implements IHelloWorldInterface {
public void sayHello() { //实现测试代理的方法
System.out.println("this is business logic in service");
}
}
真正的代理类
package com.yzy.test.dynaproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class HelloHandler implements InvocationHandler {
private Object delegate;
public HelloHandler(Object delegate) {
this.delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result;
doThisMethodBefore(); //方法执行前的操作
result = method.invoke(this.delegate, args); //执行被代理的方法
doThisMethodAfter(); //方法执行后的操作
return null;
}
private void doThisMethodAfter() {
System.out.println("before method invoke!");
}
private void doThisMethodBefore() {
System.out.println("after method invoke!");
}
}
测试
package com.yzy.test.dynaproxy.facade;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import com.yzy.test.dynaproxy.HelloHandler;
import com.yzy.test.dynaproxy.IHelloWorldInterface;
import com.yzy.test.dynaproxy.impl.HelloWorldImpl;
/**
* @author: Yangzy 2010 2010-8-24 下午02:12:20
* description: text dynamicProxy
*/
public class TestDynaProxy {
public static void main(String[] args) {
IHelloWorldInterface helloWorld = new HelloWorldImpl(); //创建一个被代理的类的对象
InvocationHandler ihHW = new HelloHandler(helloWorld); 创建一个代理类的对象
IHelloWorldInterface hwProxy = (IHelloWorldInterface)Proxy.newProxyInstance( //这里动态实现被代理的对象的控制
helloWorld.getClass().getClassLoader(),
helloWorld.getClass().getInterfaces(),
ihHW
);
hwProxy.sayHello(); //运行被代理的方法
}
}