Tuesday, February 3, 2015

Documenting Spring annotated rest interface via reflection  

1:   for (Method method : YourClass.class.getMethods()) {  
2:        // url  
3:        if (method.isAnnotationPresent(RequestMapping.class)) {  
4:          RequestMapping parms = method.getAnnotation(RequestMapping.class);  
5:          String[] val = parms.value();  
6:          RequestMethod[] methodType = parms.method();  
7:          for (int i = 0; i < val.length; i++) {  
8:            System.out.println(val[i] + "     METHOD TYPE:" + methodType[i]);  
9:          }  
10:          //parameter  
11:          Class<?>[] paramsTypes = method.getParameterTypes();  
12:          Annotation[][] annot = method.getParameterAnnotations();  
13:          for (int i = 0; i < annot.length; i++) {  
14:            if (annot[i].length > 0 && annot[i][0] instanceof RequestParam) {  
15:              RequestParam new_name = (RequestParam) annot[i][0];  
16:              System.out.println("Request: " + new_name.value() + " = " + paramsTypes[i]);  
17:            }  
18:          }  
19:          //return type  
20:          if (method.getReturnType().getCanonicalName().equals(List.class.getCanonicalName())) {  
21:            Type listType = method.getGenericReturnType();  
22:            if (listType instanceof ParameterizedType) {  
23:              Type elementType = ((ParameterizedType) listType).getActualTypeArguments()[0];  
24:              System.out.println("Response: [" + elementType + "]");  
25:            }  
26:          } else {  
27:            System.out.println("Response: " + method.getReturnType().getCanonicalName());  
28:          }  
29:        }  

No comments:

Post a Comment