来自Maven Mojo的反思

时间:2013-11-01 07:14:05

标签: java maven classloader google-reflections

我想使用Google Reflections从我的Maven插件中扫描已编译项目中的类。但默认情况下,插件不会看到项目的已编译类。从Maven 3 documentation开始,我读到了:

  

需要从项目的compile / runtime / test类路径加载类的插件需要与mojo注释@requiresDependencyResolution一起创建自定义URLClassLoader。

至少可以说有点模糊。基本上我需要一个加载已编译项目类的类加载器的引用。我怎么做到的?

编辑:

好的,@Mojo注释具有requiresDependencyResolution参数,因此很容易但仍需要正确的方法来构建类加载器。

1 个答案:

答案 0 :(得分:10)

@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);
    }
}