【问题标题】:Reflections from Maven Mojo来自 Maven Mojo 的思考
【发布时间】:2013-11-12 09:27:54
【问题描述】:

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

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

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

编辑:

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

【问题讨论】:

  • 我认为“编译(...)项目的类路径”实际上仍然是指它的依赖项,而您归结为:“需要创建自定义类加载器”。跨度>
  • 我不明白这里的拦截器是什么。 Google for custom classloader 将提供大量示例。如果一切都失败了,您还可以查看适用于项目类的现有 Maven 插件的源代码,并借用一些零碎的东西。

标签: java maven classloader reflections


【解决方案1】:
@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);
    }
}

【讨论】:

  • 如果你做 URLClassLoader loader = new URLClassLoader(projectClasspathList.toArray(new URL[0]), Thread.currentThread().getContextClassLoader());然后你作为插件依赖加载的类将是相同的实例,这将由反射返回
  • 谢谢!我的插件逻辑中有 ClassNotFoundExceptions,使用 Reflections#getAllTypes() 返回的类名,直到我 Class.forName(type, true, loader) loader 是你的加载器
猜你喜欢
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 2019-04-22
相关资源
最近更新 更多