动态代理是在学习SSH框架中很重要的知识点,Spring中的AOP编程思想也是基于动态代理来实现的。
编写动态代理时,需要注意的两点是:
1、需要Proxy代理类和继承InvocationHandle类
2、需要使用到属性思想
//动态代理
class MyProxy implements InvocationHandler
{
private Object obj; //需要动态代理的对象
public Object bind(Object obj){
this.obj=obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
}
public Object invoke(Object obj,Method method,Object[] args) throws Throwable {
return method.invoke(obj,args);
}
}
测试代码
public class TestProxy{
public static void main(String args){
IPerson person=(Person)new MyProxy().bind(new Person());
person.sayHellow("张三",34);
}
}