Java反射獲取所有Controller和RestController類的方法
引入三方反射工具Reflections
<dependency><groupId>org.reflections</groupId><artifactId>reflections</artifactId><version>0.10.2</version>
</dependency>
利用反射獲取指定包下的Controller類
public class ControllerClassHolder {public static final Reflections REFLECTION = new Reflections("com.example.controller");public static final Set<Class<?>> CLASSES;static {CLASSES = REFLECTION.getTypesAnnotatedWith(Controller.class);CLASSES.addAll(REFLECTION.getTypesAnnotatedWith(RestController.class);)}
}
獲取Controller方法
每個http請求基本都會使用@RequestMapping注解
List<Method> methods = new ArrayList<>();for (Class<?> controllerClass : CLASSES) {Method[] declaredMethods = controllerClass.getDeclaredMethods();Set<Method> methods = Arrays.stream(declaredMethods).filter(m -> m.getAnnotation(RequestMapping.class) != null).collect(Collectors.toSet());
}