Maven插件:注入项目类路径

时间:2014-11-13 06:01:14

标签: java maven plugins classpath

我正在编写一个Maven插件,其作用是委托一个需要从项目类路径中读取文件的核心模块(即项目将插件声明为插件依赖项)。

但是,根据我的理解,Maven插件附带了自己的类路径,从而导致我的核心模块中的所有Class#getResourceAsStream调用返回null。

有没有办法在插件中包含项目类路径元素?

1 个答案:

答案 0 :(得分:1)

好的,问题是由于领先的斜线。删除后,以下代码将检索MavenProject实例(您需要将maven-artifact和maven-project添加到POM中):

public static ClassLoader getClassLoader(MavenProject project) throws DependencyResolutionRequiredException, MalformedURLException {
    List<String> classPathElements = compileClassPathElements(project);
    List<URL> classpathElementUrls = new ArrayList<>(classPathElements.size());
    for (String classPathElement : classPathElements) {
        classpathElementUrls.add(new File(classPathElement).toURI().toURL());
    }
    return new URLClassLoader(
        classpathElementUrls.toArray(new URL[classpathElementUrls.size()]),
        Thread.currentThread().getContextClassLoader()
    );
}

private static List<String> compileClassPathElements(MavenProject project) throws DependencyResolutionRequiredException {
    return newArrayList(project.getCompileClasspathElements());
}
相关问题