package aop;
public interface Action {
void doAction();
}
package aop;public class ViewAction implements Action {
public void doAction() { // 做View的动作
System.out.println("You could view the information……");
}
}
package aop;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public abstract class BaseProxy implements InvocationHandler {
private Object obj;protected BaseProxy(Object obj) {
this.obj = obj;
}public static Object getInstance(Object obj, InvocationHandler instance) {
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
.getClass().getInterfaces(), instance);
}public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
Object result;try {System.out.println("before method " + m.getName());
doBegin();result = m.invoke(proxy, args);} catch (InvocationTargetException e) {throw e.getTargetException();} catch (Exception e) {throw new RuntimeException("unexpected invocation exception: "+ e.getMessage());} finally {System.out.println("after method " + m.getName());
doAfter();}return result;}public abstract void doBegin();public abstract void doAfter();}package aop;public class ProxyImpl extends BaseProxy {
protected ProxyImpl(Object o) {
super(o);
}public static Object getInstance(Object foo) {
return getInstance(foo, new ProxyImpl(foo));
}// 委派前的动作
public void doBegin() {
// TODO Auto-generated method stub
System.out.println("begin doing....haha");}// 委派后的动作
public void doAfter() {
// TODO Auto-generated method stub
System.out.println("after doing.....yeah");}}
package aop;public class Test {/**
 * @param args
 */
public static void main(String[] args) {
Action action = (Action) ProxyImpl.getInstance(new ViewAction());
action.doAction();
}
}运行Test后出现了异常,请大家指教!