温习一下 。随便写了个小demo
下面是代码
/**
* 目标对象实现的接口
*/
public interface Work {
public void add();
}
/**
* 目标对象
*/
public class WorkImpl implements Work {
public void add() {
System.out.println("我正在做加法");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 实现自己的InvocationHandler
*/
public class MyInvocation implements InvocationHandler {
private Object target=null;//目标对象
public MyInvocation(Object target) {//传入目标对象的构造方法
this.target = target;
}
/**
* 获取代理对象
*
* @return
*/
public Object bind(){
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("加法之前需要两个运算");
Object obj=method.invoke(target,args);
System.out.println("运算结束");
return obj;
}
测试类
public class Test {
public static void main(String[] args) {
Work w=new WorkImpl();
MyInvocation m=new MyInvocation(new WorkImpl());
w=(Work) m.bind();
w.add();
}
}
输出:
加法之前需要两个运算
我正在做加法
运算结束
仅供个人记录