获取Maven插件中的Java文件列表

问题描述 投票:0回答:1

有没有一种简单的方法来获取Maven插件中具有特定注释的Java文件列表?我想运行插件作为部署的一部分来调用另一个服务,该服务通知所有具有特定注释的类。

我以前在运行时使用Reflections库完成此操作,如下所示

Reflections reflections = new Reflections(PACKAGE);
Set<Class<?>> checks = reflections.getTypesAnnotatedWith(FocusCheck.class);

我认为可以通过做类似的事情来完成

 @Parameter(defaultValue = "${project}", required = true, readonly = true)
MavenProject project;

然后

List<String> compileSourceRoots = project.getCompileSourceRoots();

然后,我需要递归地查看列表中的每个文件夹,找到java文件并检查它们。我怀疑有更好的方法来做到这一点。

谢谢,保罗

java maven maven-3 maven-plugin
1个回答
0
投票

看看下面的一些Spring源代码:

注意:方法缩小以提高可读性

org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider 
/**
 * Scan the class path for candidate components.
 * @param basePackage the package to check for annotated classes
 * @return a corresponding Set of autodetected bean definitions
 */
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
    Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
    try {
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                resolveBasePackage(basePackage) + "/" + this.resourcePattern;
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        for (Resource resource : resources) {
            // check its metadata to see if it's what you want
        }
    }
    return candidates;
}

getResources()最终调用以下方法从类路径获取类资源:

org.springframework.core.io.support.PathMatchingResourcePatternResolver
/**
 * Find all class location resources with the given path via the ClassLoader.
 * Called by {@link #findAllClassPathResources(String)}.
 * @param path the absolute path within the classpath (never a leading slash)
 * @return a mutable Set of matching Resource instances
 * @since 4.1.1
 */
protected Set<Resource> doFindAllClassPathResources(String path) throws IOException {
    Set<Resource> result = new LinkedHashSet<Resource>(16);
    ClassLoader cl = getClassLoader();
    Enumeration<URL> resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path));
    while (resourceUrls.hasMoreElements()) {
        URL url = resourceUrls.nextElement();
        result.add(convertClassLoaderURL(url));
    }
    if ("".equals(path)) {
        // The above result is likely to be incomplete, i.e. only containing file system references.
        // We need to have pointers to each of the jar files on the classpath as well...
        addAllClassLoaderJarRoots(cl, result);
    }
    return result;
}

因此,似乎使用ClassLoader来获取包下的类资源,然后检查这些类的元数据是一种可行的方法。

© www.soinside.com 2019 - 2024. All rights reserved.