2017-11-29 3 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 년대 쉽게

method.getAnnotation(MethodAnnotation1.class) 

으로 처리 할 수는 불행하게도 나는 클래스 'Annotation's에 대한 예상 결과를 얻을 실패합니다. MyClass 반면 사실

,

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

반환 null에 대한 호출은 분명히 @ClassAnnotation1에 의해 주석된다.

Method 인스턴스에서 MyClass 특수 효과를 얻으려면 어떻게해야합니까?

답변

1

당신은 method.getDeclaringClass().getAnnotation(ClassAnnotation1.class)


method.getParameters()이 방법의 매개 변수는, 아마 method.getClass() 당신의 방법을 포함하는 클래스을 반환한다는 생각으로 당신을 오해 반환 사실을 사용해야합니다.

Method::getClass()은 실제로 @ClassAnnotation1으로 주석 처리되지 않은 Class<? extends Method>을 반환합니다. 그래서 당신은 null

관련 문제