【问题标题】:Get parameter value if parameter annotation exists如果参数注解存在则获取参数值
【发布时间】:2013-08-08 14:55:54
【问题描述】:

如果参数上存在注释,是否可以获得参数的值?

给定带有参数级注释的 EJB:

public void fooBar(@Foo String a, String b, @Foo String c) {...}

还有一个拦截器:

@AroundInvoke
public Object doIntercept(InvocationContext context) throws Exception {
    // Get value of parameters that have annotation @Foo
}

【问题讨论】:

    标签: java reflection annotations ejb interceptor


    【解决方案1】:

    在您的doIntercept() 中,您可以检索从InvocationContext 调用的方法并获取parameter annotations

    Method method = context.getMethod();
    Annotation[][] annotations = method.getParameterAnnotations();
    // iterate through annotations and check 
    Object[] parameterValues = context.getParameters();
    
    // check if annotation exists at each index
    if (annotation[0].length > 0 /* and if the annotation is the type you want */ ) 
        // get the value of the parameter
        System.out.println(parameterValues[0]);
    

    因为Annotation[][]在没有注解的情况下会返回一个空的二维数组,所以你知道哪些参数位置有注解。然后,您可以调用 InvocationContext#getParameters() 以获取 Object[] 并传递所有参数的值。这个数组的大小和Annotation[][] 将是相同的。只返回没有注释的索引值。

    【讨论】:

    • 这只会给我参数上的注释。我需要的是给定注释存在的参数值。
    • 不是我想要的。我不想在注释 Foo 上获取任何属性。相反,我想要参数的值。在上面的示例中,我想要参数 a 和 c 的值。
    • @user2664820 是的,刚刚更新。 method.getParameterAnnotations(); 会告诉你哪些职位,context.getParameters() 会给你价值
    【解决方案2】:

    您可以尝试这样的事情,我定义了一个名为 MyAnnotation 的 Param 注释,并以这种方式获取 Param 注释。它有效。

    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    Class[] parameterTypes = method.getParameterTypes();
    
    int i=0;
    for(Annotation[] annotations : parameterAnnotations){
      Class parameterType = parameterTypes[i++];
    
      for(Annotation annotation : annotations){
        if(annotation instanceof MyAnnotation){
            MyAnnotation myAnnotation = (MyAnnotation) annotation;
            System.out.println("param: " + parameterType.getName());
            System.out.println("value: " + myAnnotation.value());
        }
      }
    }
    

    【讨论】:

    • 您应该提供一些信息为什么您的代码可以解决问题。请看How to Answer
    • @JimHawkins 感谢您的提示。这是我第一次回答,我不知道。谢谢!
    【解决方案3】:

    你可以试试这样的

        Method m = context.getMethod();
        Object[] params = context.getParameters();
        Annotation[][] a = m.getParameterAnnotations();
        for(int i = 0; i < a.length; i++) {
            if (a[i].length > 0) {
                // this param has annotation(s)
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多