2016-06-03 2 views
0

주석 클래스 Get.javaJava 메소드에서 이름 값 주석을 전달하는 방법은 무엇입니까?

@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
@interface Get { 
    String value(); 
} 

주석 클래스 Field.java

@Target(ElementType.PARAMETER) 
@Retention(RetentionPolicy.RUNTIME) 
@interface Field { 
    String value(); 
} 

인터페이스 클래스 GetInterface.java

public interface GetInterface { 
    @Get("/group/user?") 
    void getUser(@Field("id") String id); 
} 

나는 다음이 GetInterface를 사용하려면 , 어노테이션 이름을 어떻게 얻을 수 있도록 매개 변수 속성으로 사용하여 쿼리 매개 변수로 URL을 생성하십시오

public class Request implements GetInterface { 

    @Override 
    public getUser(String id) { 
    String getPath = "/group/user?"; //How can I get this path from the annotation? 
    String name = "how can I get the name attribute 'id'????"; 
    String value = id; //this will be 123 in this example 
    //with the name an value, I can then construct a url like this 
    //https://www.foo.com/group/user?id=123 
    } 
    public static void main(String[] args) { 
    getUser("123); 
    } 
} 

답변

0

는 다음을 수행

Method m = GetInterface.class.getMethod("getUser"); 
Get getAnnotation = m.getAnnotation(Get.class) 
Field fieldAnnotation = m.getParameters()[0].getAnnotation(Field.class) 
String path = getAnnotation.value(); 
String fieldName = fieldAnnotation.value(); 
+1

'getAnnotation.value는()'하나의 문자열이 아닌 배열을 반환합니다. – VGR

+1

당신이 맞을 것 같네요! 예를 들어 다른 주석을 사용하여 코드를 작성했습니다 ... 감사합니다! 나는 그것을 고쳤다. – alexbt

관련 문제