2017-12-05 8 views
1
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.reflect.Method; 

// declare a new annotation 
@Retention(RetentionPolicy.RUNTIME) 
@interface Demo { 
    String str(); 
    int val(); 
} 

public class PackageDemo { 

    // set values for the annotation 
    @Demo(str = "Demo Annotation", val = 100) 
    // a method to call in the main 
    public static void example() { 
     PackageDemo ob = new PackageDemo(); 

     try { 
     Class c = ob.getClass(); 

     // get the method example 
     Method m = c.getMethod("example"); 

     // get the annotation for class Demo 
     Demo annotation = m.getAnnotation(Demo.class); 

     // print the annotation 
     System.out.println(annotation.str() + " " + annotation.val()); 
     } catch (NoSuchMethodException exc) { 
     exc.printStackTrace(); 
     } 
    } 
    public static void main(String args[]) { 
     example(); 
    } 
} 

내 목적은 몇 가지 메소드에서 애노테이션을 점검하고 애노테이션에 존재하는 경우 애노테이션을 가져와야한다.동적 클래스 로딩시 런타임 애노테이션 스캔

Demo annotation = m.getAnnotation(Demo.class); 

위의 예에서 주석은 동일한 파일에 선언되어 있습니다. 주석이 다른 패키지에 있으면 나는

import com.this.class.DemoClass 
try { 
     Class c = ob.getClass(); 

     // get the method example 
     Method m = c.getMethod("example"); 

     // get the annotation for class Demo 
     Demo annotation = m.getAnnotation(Demo.class); 

처럼 뭔가를 할 수하지만 동적

Class<?> Demo = Class.forName("com.this.class.DemoClass") 

처럼 DemoClass/AnnotationClass를로드하려면 어떻게 방법에 대한 주석을받을 수 있나요. 이러한 접근 방식은 근무

Class<?> Demo = Class.forName("com.this.class.DemoClass"); 
Demo annotation = m.getAnnotation(Demo); 
+0

수행하려는 작업에 대해 구체적으로 설명해 주실 수 있습니까? [최소한의 완전하고 검증 가능한 예] (https://stackoverflow.com/help/mcve)를 만들어보십시오. – fragmentedreality

+1

@fragmentedreality가 질문을 업데이트 함 일부 정보가 필요하면 알려주세요. – vjr

+0

질문의 제목을 조정하는 것이 좋습니다. "annotation processor"라는 용어는 [특정 의미] (https://stackoverflow.com/tags/annotation-processing/info)가 Java 언어 범위 안에 있습니다. 귀하의 목표에 더 적합한 용어는 * 런타임 주석 스캐닝 * 또는 간단히 [인트로 스펙 션] (https://stackoverflow.com/tags/introspection/info)입니다. – user1643723

답변

1

: 나는 아래 라인이되지 않는 주석이 동적으로로드 변수, Demo으로, 다음 주석을 얻기 위해 그 변수를 사용하는 경우이 경우

Demo annotation = m.getAnnotation(Demo.class); 
0

에서 작동 생각 나를. 이 사람이 도움이되기를 바랍니다.

DemoClass= (Class<Annotation>) Class.forName("com.this.class.DemoClass"); 
    if (method.isAnnotationPresent(DemoClass)) { 
     for (Annotation annotation : method.getAnnotations()) { 
     Class<? extends Annotation> annotationType = annotation.annotationType();  
     if (annotationType.getName() == "com.this.class.DemoClass") { 
      for (Method annotationMethod : annotationType.getDeclaredMethods()) { 
      value= annotationMethod.invoke(annotation, (Object[]) null); 
      } 
     } 
    } 
+0

시도했습니다. 나는 여기에서 2 가지 문제를 겪었다. 첫 번째는 데모가 유형으로 해석 될 수 없다는 것이며 Method 유형의 getAnnotation (Class ) 메소드는 인수에 적용 할 수 없습니다. – vjr

+0

조각난 현실에 동의합니다. 최소한의 완전하고 검증 가능한 예가 나오면 수정을 권장 할 수 있습니다. –

+0

당신이 먼저 말한 것은 제가 성취하려고하는 것입니다. 그러나 내가 말했듯이 접근법은 효과가 없습니다. 요구 사항은 명확합니다. 당신이 그것에 대해 이해하지 못하는 것을 확신하지 못합니다. 과 같은 특정 주석 클래스의 주석을 가져 오려고합니다. demo annotation = m.getAnnotation (Demo); 가져 오기를 사용하여 데모 클래스를로드 할 때 작동합니다. 그러나 Class.forname()을 사용하여 Demo.class가로드 될 때 동일한 작업을 수행하는 방법을 모릅니다. – vjr