public class DynamicAopProxy extends DynamicProxy implements InvocationHandler{
protected Object obj;
protected Pointcut pointcut;
private DynamicAopProxy(Object targetObject, Pointcut targetPointcut) {
this.obj = targetObject;
this.pointcut = targetPointcut;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
Advice advice;
advice = this.getTargetAdvice(AdviceType.BEFOREADVICE, m);
try{
advice.proceed(obj,m,args);
}
catch(AspectException ex){
ex.printStackTrace(System.out);
}
advice = this.getTargetAdvice(AdviceType.AROUNDADVICE, m);
try{
result = advice.proceed(obj,m,args);
}
catch (AspectException ex) {
ex.printStackTrace();
}
catch (Exception e) {
advice = this.getTargetAdvice(AdviceType.THROWSADVICE, m);
try {
advice.proceed(obj,m,args);
} catch (AspectException e1) {
e1.printStackTrace();
}
throw new RuntimeException
("unexpected invocation exception: " + e.getMessage());
}
finally {
System.out.println("end method " + m.getName());
}
advice = this.getTargetAdvice(AdviceType.AFTERADVICE, m);
try {
advice.proceed(obj,m,args);
} catch (AspectException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
}
return result;
}
public Advice getTargetAdvice(String type, Method m){
Advice[] advices = pointcut.getMatchAdvice(m);
for(int i=0; i<advices.length;i++){
if(advices[i].getType() == type){
return advices[i];
}
}
return new DummyAdvice();
}
public static Object newInstance(Object obj) throws FatalProxyException {
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new DynamicAopProxy(obj, null));
}
} |