【问题标题】:Reflections Library to Find All Classes within a Package用于查找包中所有类的反射库
【发布时间】:2017-03-23 04:54:30
【问题描述】:

我正在使用下面的代码来查找给定包名称中的所有类。当代码直接放入我的项目时,这工作正常。但是,从我放在一起的 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

【问题讨论】:

    标签: java reflection classpath reflections


    【解决方案1】:

    我在我们的一个项目中使用了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;
    }
    

    【讨论】:

    • 谢谢!这对我来说非常完美,并且比以前的解决方案少了很多代码。
    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2017-04-23
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多