[英]Reflections Library to Find All Classes within a Package
我使用下面的代码来查找给定包名称中的所有类。 当代码直接放入我的项目时,这很好用。 但是,从我放在一起的Commons Jar调用服务并不是从我的项目中返回数据。 这可以实现吗? 我正在使用org.reflection.Reflections库。
public Set<Class<?>> reflectPackage(String packageName){
List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());
Reflections reflections = new Reflections(
new ConfigurationBuilder().setScanners(
new SubTypesScanner(false),
new ResourcesScanner()).setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(
new ClassLoader[0]))).filterInputsBy(
new FilterBuilder().include(FilterBuilder.prefix(packageName))));
return reflections.getSubTypesOf(Object.class);
}
Project Structure
Eclipse --- Security Base // Project
| |
| --- reflectPackage("com.app.controller") call
| // Note: this package is within this project, not the Commons project.
|
--- Commons // Project
|
--- Reflector // Class
|
--- reflectPackage // Method
我在我们的一个项目中使用过Fast Classpath Scanner ,发现它非常有用。 它在类路径扫描方面有很多有用的功能。 下面显示了一个示例,它将提供有关包内的类的信息。 即使它们是第三方jar的一部分,它也会扫描并查找包/类。
public Set<Class<?>> reflectPackage(String packageName) {
final Set<Class<?>> classes = new HashSet<>();
new FastClasspathScanner("your.package.name")
.matchAllClasses(new ClassMatchProcessor() {
@Override
public void processMatch(Class<?> klass) {
classes.add(klass);
}
}).scan();
return classes;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.