一个约定游戏,即通过java的jdk动态代理实现代理类,用代理类调用方法
POJO:
public class MyRole {
private String name;
private String note;
setter/getter....
}
一个接口
public interface Service {
public void printInfo();
}
接口的实现类
public class ServiceImpl implements Service {
private MyRole role;
public ServiceImpl(MyRole role){
this.role = role;
}
@Override
public void printInfo() {
System.out.println("调用子类方法");
}
}
一个拦截器接口:
public interface Interceptor {
public void before(Object obj);
public void after(Object obj);
public void afterReturning(Object obj);
public void afterThrowing(Object obj);
}
拦截器接口的实现:
public class MyInterceptor implements Interceptor {
@Override
public void before(Object obj) {
System.out.println("before...");
}
@Override
public void after(Object obj) {
System.out.println("After....");
}
@Override
public void afterReturning(Object obj) {
System.out.println("afterReturning...");
}
@Override
public void afterThrowing(Object obj) {
System.out.println("afterThrowing...");
}
}
动态代理
public class MyProxy implements InvocationHandler {
private Service service = null;
private Interceptor interceptor = null;
//返回一个代理对象
public Object getProxy(Object target,Interceptor interceptor){
service = (Service) target;
this.interceptor = interceptor;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object retObj = null;
boolean flag = false;
interceptor.before(null);
try{
retObj = method.invoke(service,args);
}catch (Exception e){
flag = true;
}finally {
interceptor.after(null);
}
if(flag){
interceptor.afterThrowing(null);
}else {
interceptor.afterReturning(null);
}
System.out.println(retObj);
return retObj;
}
}
代码测试:
public class TestMain {
public static void main(String[] args) {
MyRole role = new MyRole();
role.setName("role1");
role.setNote("role_note");
Interceptor interceptor = new MyInterceptor();
Service service = new ServiceImpl(role);
Service proxy = (Service)new MyProxy().getProxy(service, interceptor);
proxy.printInfo();
}
// Service service = new ServiceImpl();
}
运行结果如图:
该游戏其实就是AOP的核心思想,通过动态代理实现代码的织入,从而实现调用