2017-11-29 10 views
0

は以下のclass考えてみましょう:私のアプリケーションの反射位相の間、Methodインスタンスからクラス注釈を取得するにはどうすればよいですか?

@ClassAnnotation1 
@ClassAnnotation2 
class MyClass { 

    // ...   

    @MethodAnnotation1 
    @MethodAnnotation2 
    private void myMethod(@ParamAnnotation1 @ParamAnnotation2 int i) { 
    // ... 
    } 
} 

を、私はMethodインスタンス与えられた、様々なコードの側面を分析する必要があります。

public void analyze(final Method method) { 
    // do the analysis... 
    // for example here, method is an instance of myMethod in MyClass 
} 

私は簡単に

for (Parameter p : method.getParameters()) { 
    if (p.getAnnotation(ParamAnnotation1.class) != null) { 
     // ... 
    } 
} 

を行うことにより、パラメータAnnotationを分析し、私が期待する結果を得ることができます。

方法Annotation年代を簡単残念ながら、私はクラスAnnotation年代の予想結果を得るために失敗し

method.getAnnotation(MethodAnnotation1.class) 

で処理することができます。実際に

MyClassが明確に@ClassAnnotation1で注釈されているのに対し、

method.getClass().getAnnotation(ClassAnnotation1.class)` 

への呼び出しは、nullを返します。

MethodインスタンスからMyClass注釈を取得するにはどうすればよいですか?

答えて

1

あなたがmethod.getDeclaringClass().getAnnotation(ClassAnnotation1.class)


method.getParameters()は、メソッドのパラメータは、おそらくmethod.getClass()はあなたの方法を含むクラスを返すことを考えることにあなたを欺く返すという事実を使用する必要があります。

Method::getClass()実際にはClass<? extends Method>が返されますが、これは明らかに@ClassAnnotation1によって注釈付けされていません。だからこそあなたはnull

関連する問題