java - 推断aspectj方法中参数的类型

标签 java reflection guava aspectj aop

在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/

相关文章:

java - 如何按值或计数对单词计数程序进行排序?

java - 使用 querydsl 模拟数据库查询 - 可选问题

java - Google Guava Cache - 在运行时更改驱逐超时值

java - 如何使用类参数分解 dao

java - Guava Google 在 java 中使用 Reflections

java - 消息: HTTP method POST is not supported by this URL

java - 在 java sdk 中更改语言的 DecimalFormatSymbols 符号

java - 从图像中识别数字

java - 重写方法的注释反射

c# - 如何使数据绑定(bind)控件刷新通过反射更改的属性值?