一、JdkProxy实现InvocationHandler
package test.spring.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JdkProxy<T> implements InvocationHandler {
//1.持有原始对象
private T t;
// 2.创建代理对象
public T getProxy(T t) {
/*参数一:原始对象使用的类加载对象,参数二:代理的接口的类型,参数三:增强处理 InvocantingHandler*/
this.t = t;
return (T) Proxy.newProxyInstance(t.getClass().getClassLoader(), t.getClass().getInterfaces(), this);
}
//3.增强业务逻辑处理方法
/*参数一:代理对象,参数二:当前拦截的方法,参数三:方法的参数*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object res = method.invoke(t, args);
System.out.println("after");
return res;
}
}
二、测试代码
package test.spring.proxyServices;
public interface IPrintInfo {
String printInfo(String info);
}
package test.spring.proxyServices.Impl;
import test.spring.proxyServices.IPrintInfo;
public class PrintInfo implements IPrintInfo {
public String printInfo(String info) {
System.out.println("实现类return之前执行的步骤。。。");
return info;
}
}
package test.spring.Controller.proxy;
import org.junit.Test;
import test.spring.proxy.JdkProxy;
import test.spring.proxyServices.IPrintInfo;
import test.spring.proxyServices.Impl.PrintInfo;
public class JdkProxyAction {
@Test
public void jdkProxyDemo() {
//要求被代理的对象必须是:接口+实现类 D d = new D1();
//创建代理对象
JdkProxy<IPrintInfo> handler = new JdkProxy<IPrintInfo>();
IPrintInfo d1 = handler.getProxy( new PrintInfo());
String s = d1.printInfo("hello");
// IPrintInfo printInfo = new JdkProxy<IPrintInfo>().getProxy(new PrintInfo());
// String s = printInfo.printInfo("你好!");
System.out.println(s);
}
}