<dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.10</version> </dependency>
reflections 中包含不少的Scanner ,也就是扫描器,调用对应的方法时须要有配置对应的扫描器,否则程序会抛出异常.java
//扫描包含my.package的url,包括'my.package'开头的包路径,使用默认扫描器 Reflections reflections = new Reflections("my.package");
public class testReflections { private static final Reflections reflections; static { //若是不加filterInputsBy,那么会扫描classpath,获取当前扫描路径所在项目的全部包 reflections= new Reflections(new ConfigurationBuilder() .forPackages("com.study.demo")//指定扫描路径 .filterInputsBy(new FilterBuilder().excludePackage("mystu")) //排除某个包,注意不能是扫描包子包,不然不生效 .setScanners(new MethodParameterScanner())// 添加方法参数扫描工具,能够根据须要向该方法传入多个扫描工具 ); } public static void main(String[] args) { // 一、根据方法参数,反射获取扫描路径下全部匹配的方法 Set<Method> methodsMatchParams = reflections.getMethodsMatchParams(String.class); methodsMatchParams.forEach(System.out::println); } }
//SubTypesScanner:子类扫描器 Set<Class<? extends User>> set = reflections.getSubTypesOf(User.class); // 获取void返回值方法 Set<Method> voidMethods = reflections.getMethodsReturn(void.class); // FieldAnnotationsScanner:被注解字段扫描器,获取特定注解的字段 Set<Field> fields = reflections.getFieldsAnnotatedWith(NotNull.class);
根据方法的可见性,前缀名,入参个数,获取某个类的对应方法
Set<Method> getters = ReflectionUtils.getAllMethods(User.class, withModifier(Modifier.PUBLIC), withPrefix("set"), withParametersCount(1));
根据方法入参返回值类获某个类的全部方法
//获取List的方法:入参为Collection,返回值为boolean Set<Method> methods = ReflectionUtils.getAllMethods(List.class, withParametersAssignableTo(Collection.class), withReturnType(boolean.class));
获取某个类特定类型的全部字段
//该方法能够传入一些参数,好比过滤出带注解的参数:withAnnotation(NonNull.class) Set<Field> fields = ReflectionUtils.getAllFields(Animal.class, withTypeAssignableTo(String.class));