反射工具包reflections
帮助开发者通过反射扫描指定路径下的类、方法等
maven依赖
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>
小例子
package com.lucas.device.rest.api;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.Set;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* <Description> <br>
*
* @author xubin<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2019/9/18 <br>
*/
public class Demo {
/**
* Description: 打印指定路径下api请求地址<br>
*
* @author xubin <br>
* @taskId <br>
* @param args <br>
*/
public static void main(String[] args) {
String packagePath = "com.lucas.device.rest.api";
Reflections reflections = new Reflections(
new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(packagePath)).setScanners(new MethodAnnotationsScanner()));
Set<Method> methodSet = reflections.getMethodsAnnotatedWith(PostMapping.class);
for (Method m : methodSet) {
String classMapping = m.getDeclaringClass().getAnnotation(RequestMapping.class).value()[0];
String[] value = m.getAnnotation(PostMapping.class).value();
if (Objects.nonNull(value) && value.length > 0)
System.out.println(String.format("methodName:%s,postMapping:%s", m.getName(),
classMapping + m.getAnnotation(PostMapping.class).value()[0]));
}
}
}