被代理對象的接口:
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);
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26689.html