2013-08-08 24 views
5

注釈がそのパラメータに存在する場合、パラメータ値を取得できますか?パラメータ注釈が存在する場合にパラメータ値を取得

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

そしてインターセプター:あなたのdoIntercept()

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

答えて

4

あなたはInvocationContextから呼び出されるメソッドを取得してparameter annotationsを得ることができます

は、パラメータレベルのアノテーションでEJBを考えます。

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[][]のサイズは同じです。注釈がない場合はインデックスの値を返します。

+0

これは、パラメータに存在するアノテーションのみを私に与えます。私が必要とするのは、アノテーションが存在する場合のパラメータの値です。 – user2664820

+0

私が探しているものではありません。注釈Fooの属性を取得しようとしていません。むしろ、私はパラメータの値が必要です。上記の私の例では、引数aとcの値が必要です。 – user2664820

+0

@ user2664820うん、ちょうど更新されました。 'method.getParameterAnnotations();'は、どの位置に 'context.getParameters()'が値を与えるのかを教えてくれます –

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) 
     } 
    } 
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()); 
    } 
    } 
} 
+1

あなたのコードが問題を解決する理由を説明してください。 [回答] – JimHawkins

+0

@JimHawkinsを見てください。あなたのヒントをありがとう。これは私の最初の答えであり、私はそれを知らなかった。ありがとう! – franlisa

関連する問題