我想使用谷歌反射扫描从我的Maven插件编译的项目的类。但是默认情况下,插件看不到项目的编译类。我从Maven 3 documentation上读到:
需要从项目的编译/运行时/测试类路径加载类的插件需要与mojo注释@requiresDependencyResolution结合创建一个自定义URLClassLoader。
至少可以说是有点模糊。基本上,我需要一个对加载编译项目类的类加载器的引用。我怎么弄到那个?
编辑:
好的,@Mojo注释有requiresDependencyResolution参数,所以这很容易,但仍然需要正确的方法来构建类加载器。
发布于 2013-11-01 12:10:02
@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);
}
}https://stackoverflow.com/questions/19722366
复制相似问题