[英]Reflections Library to Find All Classes within a Package
I am using the below code to find all of the Classes within a given package name. 我使用下面的代码来查找给定包名称中的所有类。 This works fine when the code is placed directly into my project.
当代码直接放入我的项目时,这很好用。 However, calling the service from a Commons Jar I put together isn't returning the data from my project.
但是,从我放在一起的Commons Jar调用服务并不是从我的项目中返回数据。 Can this be achieved?
这可以实现吗? I am using org.reflection.Reflections library.
我正在使用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
I have used Fast Classpath Scanner in one of our projects and found it really useful. 我在我们的一个项目中使用过Fast Classpath Scanner ,发现它非常有用。 It has a lot of useful functionalities when it comes to class path scanning.
它在类路径扫描方面有很多有用的功能。 An example is shown below which will give information about classes inside a package.
下面显示了一个示例,它将提供有关包内的类的信息。 It will scan and find packages/classes even if they are part of a third party jar.
即使它们是第三方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.