gpt4 book ai didi

java - 来自 Maven Mojo 的思考

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:17:26 25 4
gpt4 key购买 nike

我想使用 Google Reflections 从我的 Maven 插件编译的项目中扫描类。但是默认情况下插件看不到项目的编译类。来自 Maven 3 documentation我阅读:

Plugins that need to load classes from the compile/runtime/test class path of a project need to create a custom URLClassLoader in combination with the mojo annotation @requiresDependencyResolution.

至少可以说这有点含糊。基本上我需要一个类加载器的引用来加载已编译的项目类。我如何获得它?

编辑:

好的,@Mojo 注释有 requiresDependencyResolution 参数,所以这很简单,但仍然需要正确的方法来构建类加载器。

最佳答案

@Component
private MavenProject project;

@SuppressWarnings("unchecked")
@Override
public void execute() throws MojoExecutionException {
List<String> classpathElements = null;
try {
classpathElements = project.getCompileClasspathElements();
List<URL> projectClasspathList = new ArrayList<URL>();
for (String element : classpathElements) {
try {
projectClasspathList.add(new File(element).toURI().toURL());
} catch (MalformedURLException e) {
throw new MojoExecutionException(element + " is an invalid classpath element", e);
}
}

URLClassLoader loader = new URLClassLoader(projectClasspathList.toArray(new URL[0]));
// ... and now you can pass the above classloader to Reflections

} catch (ClassNotFoundException e) {
throw new MojoExecutionException(e.getMessage());
} catch (DependencyResolutionRequiredException e) {
new MojoExecutionException("Dependency resolution failed", e);
}
}

关于java - 来自 Maven Mojo 的思考,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19722366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com