簡體   English   中英

如何在Java方法中傳遞名稱值注釋?

[英]How to pass name value annotation in Java method?

注釋類Get.java

@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,如何獲取批注名稱,以便可以將其用作參數屬性來構造具有查詢參數的get 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);
  }
}

請執行下列操作:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM