6

パラメータに注釈が存在する場合、そのパラメータの値を取得することは可能ですか?

パラメータ レベルのアノテーションを持つ 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
}
4

3 に答える 3

7

doIntercept()から呼び出されているメソッドをInvocationContext取得し、パラメータ アノテーションを取得できます。

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[][]アノテーションがない場合、 は空の 2 次元配列を返すため、どのパラメーター位置にアノテーションがあるかがわかります。その後、 を呼び出して、渡されたすべてのパラメーターの値InvocationContext#getParameters()を取得できます。Object[]この配列と のサイズはAnnotation[][]同じになります。注釈がないインデックスの値を返すだけです。

于 2013-08-08T15:01:13.023 に答える
1

このようなものを試すことができます

    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)
        }
    }
于 2013-08-08T15:06:26.373 に答える