java反射工具Reflections用法

一、引入maven依赖

    <dependency>
       <groupId>org.reflections</groupId>
       <artifactId>reflections</artifactId>
       <version>0.9.10</version>
    </dependency>

二、用法示例:

reflections 中包含很多的Scanner ,也就是扫描器,调用对应的方法时需要有配置对应的扫描器,不然程序会抛出异常.

//扫描包含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) {
        // 1、根据方法参数,反射获取扫描路径下所有匹配的方法
        Set<Method> methodsMatchParams = reflections.getMethodsMatchParams(String.class);
        methodsMatchParams.forEach(System.out::println);
    }
}

相关Api

一些扫描器

//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);

ReflectionUtils

根据方法的可见性,前缀名,入参个数,获取某个类的对应方法
 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));

java

 

http://www.mianshigee.com/tutorial/hutool/f63b669ba259e4f6.md   java知识

 

Guess you like

Origin blog.csdn.net/u010074988/article/details/117994137