s-hunter s-hunter - 6 months ago 11
Java Question

How to pass name value annotation in Java method?

The annotation class Get.java

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


The annotation class Field.java

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


The interface class GetInterface.java

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


I want to use this GetInterface in the following, how can I get the annotation name so I can use that as the parameter attribute to construct a get url with query parameters

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

Answer

Do the following:

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