Maven插件无法加载类 [英] Maven plugin can't load class

查看:524
本文介绍了Maven插件无法加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个需要使用反射的Maven插件.我希望一个项目运行该插件,并在项目中为其提供类的全名,然后该插件将通过反射加载该插件以从中获取信息.

I'm trying to make a maven plugin that needs to use reflection. I want a project to run the plugin, and give it the full name of a class in the project, and the plugin will load it by reflection to get info from it.

虽然类加载器有一些奇怪之处,因为当我使用它时找不到类

There's something strange with the classloader though, because it can't find the class when I use

Class.forName("package.MyClass");

查看" Maven类加载指南",我无法弄清楚我的插件的类加载器在其他项目中运行时是否可以访问该项目的类.

Looking at the "Guide to Maven Classloading", I can't quite figure out if my plugin's classloader, when being run in a different project, has access to that project's classes.

推荐答案

我敢肯定有更好的方法,但是这就是我的工作方式:

I'm sure there's a better way, but here's how I got it to work:

将以下内容添加到mojo顶部的javadoc中: @requiresDependencyResolution运行时

Add the following to the javadoc at the top of your mojo: @requiresDependencyResolution runtime

添加一个MavenProject参数:

Add a MavenProject parameter:

/**
 * @parameter expression="${project}"
 * @required
 * @readonly
 */
private MavenProject project;

然后,您可以在运行时获取依赖项,并创建自己的类加载器:

Then you can get the dependencies at runtime, and make your own classloader:

List runtimeClasspathElements = project.getRuntimeClasspathElements();
URL[] runtimeUrls = new URL[runtimeClasspathElements.size()];
for (int i = 0; i < runtimeClasspathElements.size(); i++) {
  String element = (String) runtimeClasspathElements.get(i);
  runtimeUrls[i] = new File(element).toURI().toURL();
}
URLClassLoader newLoader = new URLClassLoader(runtimeUrls,
  Thread.currentThread().getContextClassLoader());

然后,您可以使用此新的类加载器加载类:

Then you can load your class using this new classloader:

Class bundle = newLoader.loadClass("package.MyClass");

这篇关于Maven插件无法加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆