【问题标题】:How to get parameter name in aspectj advice class?如何在 aspectj 建议类中获取参数名称?
【发布时间】:2017-03-21 18:31:16
【问题描述】:

我以我对 Java 反射和 AOP 的有限知识提出这个问题。

背景:

我在我的 Java 7 应用程序中使用基于注解的建议。为了进一步获得我需要在我的建议中使用的方法参数,我正在使用 spring EL。请参见以下示例: 在第一个示例中,我想使用第二个参数来完成我的工作,而在第二个示例中,我使用 POJO 并希望使用它的“id”字段。

@MyAnnotation(param = "args[1]")
public void someMethod(int param1, String param2) {
  return null;
}

@MyAnnotation(param = "args[0].id")
public void someMethod(SomeObject someObject) {
  return null;
}

但我真正想要的是,在我的 AOP 中获得参数名称。这样我就可以使用 @MyAnnotation(param = "param1") 或 @MyAnnotation(param = "someObject.id") 代替。

据我所知,您无法使用反射获取参数名称。但是最近我遇到了 Spring 缓存抽象(link),我看到:

@Cacheable(cacheNames="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

有人可以在这里说明一下,我如何实现类似的行为。

【问题讨论】:

    标签: reflection annotations aop spring-el


    【解决方案1】:

    参见MethodBasedEvaluationContext 和ParameterNameDiscoverer。

    CacheEvaluationContext 是MethodBasedEvaluationContext 的子类。

    Code here...

        // Expose indexed variables as well as parameter names (if discoverable)
        String[] paramNames = this.parameterNameDiscoverer.getParameterNames(this.method);
        int paramCount = (paramNames != null ? paramNames.length : this.method.getParameterCount());
        int argsCount = this.arguments.length;
    
        for (int i = 0; i < paramCount; i++) {
            Object value = null;
            if (argsCount > paramCount && i == paramCount - 1) {
                // Expose remaining arguments as vararg array for last parameter
                value = Arrays.copyOfRange(this.arguments, i, argsCount);
            }
            else if (argsCount > i) {
                // Actual argument found - otherwise left as null
                value = this.arguments[i];
            }
            setVariable("a" + i, value);
            setVariable("p" + i, value);
            if (paramNames != null) {
                setVariable(paramNames[i], value);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 2023-02-01
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      相关资源
      最近更新 更多