s-hunter s-hunter - 1 year ago 107
Java Question

How to pass name value annotation in Java method?

The annotation class Get.java

@interface Get {
String value();

The annotation class Field.java

@interface Field {
String value();

The interface class GetInterface.java

public interface GetInterface {
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 {

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
public static void main(String[] args) {

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download