Java annotation for constructing GET request url

Java annotation is for embedding metadata into the source code, it doesn’t have direct effect on the logic of the source code. It is used for providing instructions to the compiler. There are compile time instructions and runtime instructions. @Deprecated, @Override and @SuppressWarnings are three built in annotation.

Take the annotation @Override as an example, when you are overriding a method in the parent class, you can overriding it by declaring the same method name with the same parameters in the child class. You can omit the annotation @Override and it will work fine, but if you accidentally misspelled the method name by just one letter, your program will still be able to compile but you won’t notice this bug until you found some unexpected behaviors of your program. Thus, by adding the @Override annotation at the beginning of the method that is suppose to override the method method, the compiler will tell that you’ve made a mistake right away and it also makes your code more readable.

Even though annotation is for providing metadata and not for doing any logic in the source code, but we can still utilize the information provided in the metadata. The following is an example of more practical usage of annotation. We are going to create two annotations @Get and @Field, the use them to create a http get request url. The result will be, you call a method getUser(“123”), it will give you a get request url similar to http://www.foo.com/group/user?id=123

Get.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

Field.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

GetInterface.java

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

    @Get("/genre/book")
    void getBook(@Field("isbn") String isbn);
}

Request.java

import java.lang.reflect.Method;
public class Request implements GetInterface {
    public static final String BASEURL = "http://www.foo.com";
    @Override
    public void getUser(String id) {
        String baseUrl = BASEURL;
        try {
            //getting the path
            Method m = GetInterface.class.getMethod("getUser", String.class);
            Get getAnnotation = m.getAnnotation(Get.class);
            String path = getAnnotation.value();

            //getting the method parameter attribute
            Field fieldAnnotation = m.getParameters()[0].getAnnotation(Field.class);
            String fieldName =  fieldAnnotation.value();

            //Construct the final url
            String endpoint = baseUrl + path + "?" + fieldName + "=" + id;
            System.out.println(endpoint);
            System.out.println(" --------------------------- ");
        } catch (Exception e) {
            System.out.println("getUser " + e);
        }

    }

    @Override
    public void getBook(String isbn) {
        String baseUrl = BASEURL;
        try {
            //getting the path
            Method m = GetInterface.class.getMethod("getBook", String.class);
            Get getAnnotation = m.getAnnotation(Get.class);
            String path = getAnnotation.value();

            //getting the method parameter attribute
            Field fieldAnnotation = m.getParameters()[0].getAnnotation(Field.class);
            String fieldName =  fieldAnnotation.value();

            //Construct the final url
            String endpoint = baseUrl + path + "?" + fieldName + "=" + isbn;
            System.out.println(endpoint);
            System.out.println(" --------------------------- ");
        } catch (Exception e) {
            System.out.println("getUser " + e);
        }
    }

    private static void printAnnotationValues() {
        String baseUrl = BASEURL;
        String endpoint = "";
        Class getInterface = GetInterface.class;
        for (Method method : getInterface.getMethods()) {
            endpoint = "";
            Get getAnnotation = (Get) method.getAnnotation(Get.class);
            if (getAnnotation != null) {
                System.out.println(" Method Name : " + method.getName());
                System.out.println(" Get : " + getAnnotation.value());
                endpoint = baseUrl + getAnnotation.value();
            }

            Field fieldAnnotation = (Field) method.getParameters()[0].getAnnotation(Field.class);
            if (fieldAnnotation != null) {
                System.out.println(" Field : " + fieldAnnotation.value());
                endpoint = baseUrl + getAnnotation.value() + "?" + fieldAnnotation.value() + "=";
            }
            System.out.println(" endpoint : " + endpoint);
            System.out.println(" --------------------------- ");
        }        
    }

    public static void main(String[] args) {
        printAnnotationValues();
        Request request = new Request();
        request.getUser("111");
        request.getBook("789");
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search