微科社区,轻松开发从此开始! 请登陆 免费注册

微科社区

当前位置:首页 > Java平台 > J2EE >

AOP面向切面编程(5)

时间:2017-01-12 04:01  浏览:努力统计中...
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println( begin valid method [ +method.getName()+ ] with args +Arrays.toString(args)); for (Object arg :
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
System.out.println("begin valid method ["+method.getName()+"] with args "+Arrays.toString(args));

for(Object arg : args)
{
this.argValidtor((Double)arg);
}

Object result = method.invoke(this.target, args);

return result;
}

/*获取代理类*/
public Object getProxy()
{
return Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this);
}

private void argValidtor(double arg) throws Exception
{
if(arg < 0)
throw new Exception("参数不能为负数!");
}
}

场景类调用:

public class Client
{
public static void main(String[] args) throws Exception
{
/*获得代理*/
Calculator arithmeticCalculatorProxy = (Calculator)new ArithmeticCalculatorInvocationHandler(
new ArithmeticCalculator()).getProxy();

Calculator argValidatorProxy = (Calculator)new ArithmeticCalculatorArgsInvocationHandler(arithmeticCalculatorProxy).getProxy();

/*调用add方法*/
argValidatorProxy.add(10, 10);
}
}

控制台输出:

begin valid method [add] with args [10.0, 10.0]
the method [add]begin with args ([10.0, 10.0])
the method [add]end with result (20.0)

输入一个负数数据:

public class Client
{
public static void main(String[] args) throws Exception
{
/*获得代理*/
Calculator arithmeticCalculatorProxy = (Calculator)new ArithmeticCalculatorInvocationHandler(
new ArithmeticCalculator()).getProxy();

Calculator argValidatorProxy = (Calculator)new ArithmeticCalculatorArgsInvocationHandler(arithmeticCalculatorProxy).getProxy();

/*调用add方法*/
argValidatorProxy.add(-10, 10);
}
}

控制台输出:

begin valid method [add] with args [-10.0, 10.0]
Exception in thread "main" java.lang.Exception: 参数不能为负数!
at com.beliefbetrayal.aop.ArithmeticCalculatorArgsInvocationHandler.argValidtor(ArithmeticCalculatorArgsInvocationHandler.java:46)
at com.beliefbetrayal.aop.ArithmeticCalculatorArgsInvocationHandler.invoke(ArithmeticCalculatorArgsInvocationHandler.java:29)
at $Proxy0.add(Unknown Source)
at com.beliefbetrayal.aop.Client.main(Client.java:14)

 

顶一下
(2)
100%
踩一下
(0)
0%
------分隔线------
栏目列表
推荐内容