被代理对象的接口:
package testdynamicproxy;
public interface TargetInterface {
public void SayHello();
public int sum(int a int b);
}
被代理的对象:
package testdynamicproxy;
public class Target implements TargetInterface {
public void SayHello(){
Systemoutprintln(Hello);
}
public int sum(int a int b) {
return a+b;
}
}
InvocationHandler包装:
package testdynamicproxy;
import javalangreflectInvocationHandler;
import javalangreflectMethod;
public class TargetInvocationHandler implements InvocationHandler {
private Object object;
public TargetInvocationHandler(Object obj){
thisobject=obj;
}
public Object invoke(Object proxy Method method Object[] args)
throws Throwable
{
doBefore();
Object result = methodinvoke(object args);
doAfter();
return result;
}
public void doBefore(){
Systemoutprintln(do before);
}
public void doAfter(){
Systemoutprintln(do after);
}
}
测试类:
package testdynamicproxy;
import javalangreflectProxy;
public class TestDynamicProxy {
/**
* @param args
*/
public static void main(String[] args) {
Target t=new Target();
TargetInvocationHandler handler=new TargetInvocationHandler(t);
TargetInterface proxy = (TargetInterface) ProxynewProxyInstance(
tgetClass()getClassLoader()
tgetClass()getInterfaces()
handler);
proxySayHello();
int b=proxysum( );
Systemoutprintln(b);
}
}