java 反射中没有直接提供给我们方法来根据接口获取所有实现的类,所以要自己去写,网上资料也很多,根据通过ClassLoader获取当前工作目录,对目录下的文件进行遍历扫描。
大致思路:
1) 获取当前线程的ClassLoader
2) 通过ClassLoader获取当前工作目录,对目录下的文件进行遍历扫描。
3) 过滤出以.class为后缀的类文件,并加载类到list中
4) 对list中所有类进行校验,判断是否为指定接口的实现类,并排除自身。
5) 返回所有符合条件的类。
这个思路是对的,但是考虑不全,不能拿来工程应用,另外博文中提供的源码应该只是一个实验代码,有不少缺陷。
我看了就这种方法比较靠谱点,其他的好像都有问题。
自己写ClassLoader太累,还有我们工具包reflections,这个是反射集合,需要引入jar
<dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.10</version> </dependency>
public static void reflectTest() { //指定扫描的包名 Reflections reflections = new Reflections("pattern.duty"); //Filter是个接口,获取在指定包扫描的目录所有的实现类 Set<Class<? extends Filter>> classes = reflections.getSubTypesOf(Filter.class); for (Class<? extends Filter> aClass : classes) { System.out.println(aClass.getName()); } }
就是这么简单,主要关键点是指定扫描包的路径。所以做成项目jar包时候,你要开个注册机制填写扫描包路径。
以下又很多用法,构造方法里填入不同的扫描器,扫描不能的功能,如要获取注解,就加入注解扫描器
public static void reflectionsTest() { // 扫包 Reflections reflections = new Reflections(new ConfigurationBuilder() .forPackages("com.boothsun.reflections") // 指定路径URL .addScanners(new SubTypesScanner()) // 添加子类扫描工具 .addScanners(new FieldAnnotationsScanner()) // 添加 属性注解扫描工具 .addScanners(new MethodAnnotationsScanner()) // 添加 方法注解扫描工具 .addScanners(new MethodParameterScanner()) // 添加方法参数扫描工具 ); // 反射出子类 Set<Class<? extends Filter>> set = reflections.getSubTypesOf(Filter.class); System.out.println("getSubTypesOf:" + set); // 反射出带有指定注解的类 Set<Class<?>> ss = reflections.getTypesAnnotatedWith(NotMapper.class); System.out.println("getTypesAnnotatedWith:" + ss); // 获取带有特定注解对应的方法 Set<Method> methods = reflections.getMethodsAnnotatedWith(NotMapper.class); System.out.println("getMethodsAnnotatedWith:" + methods); // 获取带有特定注解对应的字段 Set<Field> fields = reflections.getFieldsAnnotatedWith(Autowired.class); System.out.println("getFieldsAnnotatedWith:" + fields); // 获取特定参数对应的方法 Set<Method> someMethods = reflections.getMethodsMatchParams(long.class, int.class); System.out.println("getMethodsMatchParams:" + someMethods); Set<Method> voidMethods = reflections.getMethodsReturn(void.class); System.out.println("getMethodsReturn:" + voidMethods); Set<Method> pathParamMethods = reflections.getMethodsWithAnyParamAnnotated(NotMapper.class); System.out.println("getMethodsWithAnyParamAnnotated:" + pathParamMethods); }