jdk1.3之后版本 支持动态代理,主要有2个类:java.lang.reflect.Proxy类和java.lang.reflect.InvocationHandler接口;使用动态代理必须有接口。
1.定义接口IRequestCtr
public interface IRequestCtr {
public String getRequest();
}
2.接口实现类
public class RequestCtrImpl implements IRequestCtr {
@Override
public String getRequest() {
System.out.println("运行方法");
return "jia";
}
}
3.实现InvocationHandler编写横切面逻辑
public class InverCtrHandler implements InvocationHandler {
private Object target;
public InverCtrHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理前");
method.invoke(target,args);
System.out.println("代理后");
return null;
}
}
4.main测试类
public class ProxyTest {
public static void main(String[] args) {
IRequestCtr reqProxy = (IRequestCtr)Proxy.newProxyInstance(ProxyTest.class.getClassLoader()
, new Class[]{IRequestCtr.class}
, new InverCtrHandler(new RequestCtrImpl()));
reqProxy.getRequest();
}
}
最终运行结果:
代理前
运行方法
代理后