Search code examples
javarestpathrestful-urlrequest-mapping

How to programmatically read the path of a rest service?


suppose I have the following simple rest defined:

@RequestMapping("/user/data")
@ResponseBody
public String getUserDetails(@RequestParam int id) {
    ...
}

Is there a way to read the path string problematically by another part of the code (i.e. from a different method altogether) ? Something like:

String restPath = SomeReflection.getPath("getuserdetails"); // received value: "/user/data"

WDYT? thanks!

Solved! here's the implementation I needed:

public String getUrlFromRestMethod(Class controllerClass, String methodName) {

        try {
            Method method = controllerClass.getMethod(methodName);
            if (method != null && method.isAnnotationPresent(RequestMapping.class)) {

                RequestMapping requestMappingAnnotation = method.getAnnotation(RequestMapping.class);
                return requestMappingAnnotation.toString();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();//TODO
        }

        return null;
    }

Solution

  • If you mean that you wanna access that value programmatically even from another class, then maybe you can start working out your solution from this example:

        //get all methods defined in ClassA
        Method[] methods = ClassA.class.getMethods();
        for (Method m : methods) {
            //pick only the ones annotated with "@RequestMapping"
            if (m.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping ta = m.getAnnotation(RequestMapping.class);
                System.out.println(ta.value()[0].toString());
            }
        }