一、实现InvacatinHandler
Exmaple:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationhandler implements InvocationHandler{
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO 调用一个类方法在其开始和结束时分别先执行method1和method2
Dogutil du=new Dogutil();
//要开始时插入的method1方法
du.method1();
//Object result=invoke(target, method, args);
Object result=method.invoke(target,args);
//要结束时插入的method1方法
du.method2();
return result;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
}
二、实现proxyfactory
Example:
import java.lang.reflect.Proxy; public class proxyfactory { public static Object getproxy(Object traget){ MyInvocationhandler handler=new MyInvocationhandler(); handler.setTarget(traget); return Proxy.newProxyInstance(traget.getClass().getClassLoader(), traget.getClass().getInterfaces(), handler); } }
三、编写测试类。
Example:
public class test { /** * @param args */ public static void main(String[] args) { // TODO 使用代理调用gundog类方法 Dog traget=new gundog(); Dog dog =(Dog)proxyfactory.getproxy(traget); dog.info(); dog.run(); } }