注释类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);
}
}
答案 0 :(得分: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();