java:反射获取Package下接口的全部实现类
1 使用
依赖导入:
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
使用:
package xiaoxu.project;
import org.reflections.Reflections;
import org.springframework.util.StringUtils;
import java.util.Set;
/**
* @author xiaoxu
* @date 2023-04-12
* java_demo3:xiaoxu.project.ReflectClassGet
*/
public class ReflectClassGet {
public static void main(String[] args) {
Set<Class<? extends Fr>> subClasses = getSubClasses("xiaoxu.project", Fr.class);
for (Class<? extends Fr> subClass : subClasses) {
System.out.println(subClass.getPackage().getName() + "." + subClass.getSimpleName());
}
}
public static <T> Set<Class<? extends T>> getSubClasses(String packageName, Class<T> parentClazz){
if(!StringUtils.hasLength(packageName)){
throw new RuntimeException("packageName access empty");
}
if(null == parentClazz){
throw new RuntimeException("parentClazz is null");
}
Reflections reflects = new Reflections(packageName);
return reflects.getSubTypesOf(parentClazz);
}
}
interface Fr{}
class AFr implements Fr{}
class BFr implements Fr{}
class CFr implements Fr{}
执行结果:
12:54:29.518 [main] INFO org.reflections.Reflections - Reflections took 140 ms to scan 1 urls, producing 9 keys and 15 values
xiaoxu.project.BFr
xiaoxu.project.AFr
xiaoxu.project.CFr