在AOP(使用Aspectj)中我们可以使用拦截方法调用并访问其参数
Object[] args=joinPoint.getArgs();
但是 JoinPoint 类是否为我们提供了推断参数类型的功能?例如:
public void setApples(List<Apple>){..}
我得到的只是一个Object
实例。有没有某种方法可以使用joinpoint
属性或反射或Guava TypeToken
来推断该参数的类型?
最佳答案
如果参数不为空,您可以使用 @Babur 在评论中所写的 instanceof
检查类型,或者在不为空时检查其Class
:
Object[] args = joinPoints.getArgs();
if (args[0] instanceof String) {
System.out.println("First arg is a String of length " + ((String) args[0]).length());
}
if (args[1] == null) {
System.out.println("Second arg is null");
} else {
System.out.println("Second arg is a " + args[1].getClass());
}
如果确实需要分析方法的参数,可以强制转换 jointPoint.getSignature()
到 MethodSignature
访问Method
:
if (joinPoint.getSignature() instanceof MethodSignature) {
Method method = ((MethodSignature) jointPoint.getSignature()).getMethod();
System.out.println("Method parameters: " + Arrays.toString(method.getParameterTypes()));
}
关于java - 推断aspectj方法中参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31721702/