반사

2013-07-30 5 views
3

를 통해 자바 주석에 대한 정보를 얻기 나는이 주석 형 클래스가 있습니다반사

import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 

@Retention(RetentionPolicy.RUNTIME) 
public @interface RemoteTcpAccess { 

    public int port(); 
} 

와 같은 다른 클래스에 적용 :

@RemoteTcpAccess(port = 444) 
public class CalculatorService { 

    public int Add(int a, int b) { 
     return a + b; 
    } 

    public void DisplayText(String text) { 
     System.out.println(text); 
    } 
} 

지금 나는 CalculatorService 클래스 객체를 얻고 시도 RemoteTcpAccess 주석에 대한 정보를 얻으려면 :

private static void CheckRemoteTcpAccess(List<Class> classes) { 
     for (Class class1 : classes) { 
      for (Annotation annotation : class1.getDeclaredAnnotations()) { 
       if (AnnotationEquals(annotation, ComponentsProtocol.REMOTE_TCP_ACCESS)) { 
      //GET INFORMATION 
       } 
      } 
     } 
    } 

    private static boolean AnnotationEquals(Annotation classAnnotation, String protocolAnnotation) { 
     return classAnnotation.toString() 
       .substring(0, classAnnotation.toString().indexOf("(")) 
       .equals(protocolAnnotation); 
    } 

나는 인식 할 수있다. 클래스가에 RemoteTcpAccess 주석을 적용했다,하지만 난 주석을 가지고 있으며, 어떤 필드에 대한 inforamtion를 얻을하지 못할 경우처럼 해당 필드, 무슨 값 :

필드 포트 - 값을 444

어떻게 얻을 방법이 있나요 반사를 통해 그 inforamtion?

감사

답변

0

코드가 주석을 확인 입력해야 if가 RemoteTcpAccess 유형인지 확인하십시오. 그렇다면 AnnotationRemoteTcpAccess 유형으로 전송합니다. 이 유형에서 port을 검색 할 수 있습니다.

import java.lang.annotation.Annotation; 

@RemoteTcpAccess(port = 322) 
public class AnnotationTest { 

    /** 
    * @param args 
    * @throws NoSuchFieldException 
    * @throws SecurityException 
    */ 
    public static void main(String[] args) throws SecurityException, 
      NoSuchFieldException { 
     Annotation anno = AnnotationTest.class 
       .getAnnotation(RemoteTcpAccess.class); 
     if (anno instanceof RemoteTcpAccess) { 
      RemoteTcpAccess rta = (RemoteTcpAccess) anno; 
      System.out.println(rta.port()); 
     } 
    } 
} 
+0

매우 유용합니다, 나는 instanceof 키워드를 확인합니다! 하지만 항상 instanceof RemoteTcpAccess 아니에요? –

+1

@ JohnSmith이 예에서는 네,하지만 상황을 생각해보십시오 (특수 효과를 통해 반복). 클래스에 여러 개의 주석이있는 경우 'RemoteTcpAccess' 유형이 아닐 수도 있습니다. 맹목적으로 캐스팅을 수행하고 나중에 클래스가 주석을 얻으면 코드가 중단됩니다. –

1

((RemoteTcpAccess)annotation).port(); 
+0

간단하고 작동 :) 감사합니다 –

2

당신은 호출 할 수 있습니다 시도해보십시오

RemoteTcpAccess rta = clazz.getAnnotation(RemoteTcpAccess.class); 
if(rta != null) //annotation present at class level 
{ 
int port = rta.port(); 
} 

귀하의 경우에는 직접 특정 주석 (RemoteTcpAccess) 대신 Annotation를 사용하는 일반적인 방법을 사용할 수 있습니다. 그래서이 당신의 루프 아래 트림 것이다 인터페이스와 주석 사이의 ananlogy에 대해 알고에서

for (Class class1 : classes) { 
    RemoteTcpAccess rta = class1.getAnnotation(RemoteTcpAccess.class); 
    if(rta != null) { 
     int port = rta.port(); //GET INFORMATION 
     .. 
    } 
} 
0

을, 나는이 일 것이라고 말하고 싶지만 :

((RemoteTcpAccess) annotation).getPort()