spring动态代理
1.实现方法
package com.zhu.Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//实现InvocationHandler接口
public class ProxyInvocationHandler implements InvocationHandler {
// 定义一个Object类的变量。
private Object target;
public void setTarget(Object target) {
this.target = target;
}
public Object getProxy(){
// this.getClass().getClassLoader() :本类的类加载器
// target.getClass().getInterfaces():目标类的接口
// this:调用处理程序(也就是本类)
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
}
// 处理代理对象,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target,args);
return result;
}
}
2.测试代码
package com.zhu.Proxy;
import com.zhu.pojo.Student;
import com.zhu.pojo.StudentImpl;
public class Test {
public static void main(String[] args){
// 创建一个真实对象
StudentImpl student = new StudentImpl();
// 生成一个代理对象
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
proxyInvocationHandler.setTarget(student);
Student student1 = (Student) proxyInvocationHandler.getProxy();
// 执行方法
student1.put();
}
}
提示;
proxy有一个方法(newProxyInstance)可以创建一个代理对象。参数是,该类的类加载器,和被代理的接口,和调用处理程序。
invoke方法是处理代理实例,并且返回结果的。
每一个代理实例都有一个调用处理程序
还没有评论,来说两句吧...