MavenProject: Get the available classes for use on

2019-07-29 22:42发布

问题:

I'm loading a Maven project as described here. I'm trying to figure out how I can retrieve the source roots so I can figure out the Java classes I have so my Mojo can use them.

I tried a couple of the methods in there, like getResources or getScriptSources without luck. Any idea?

Thanks in advance!

Edit:

I was asked to elaborate a little bit in what I'm attempting to do, so here it is:

The plugin I'm developing will take the sources in the project and create test cases from those. Unless configured, I want to generate tests for all the classes, and for that, I need to somehow figure out where are my sources so I can configure properly.

Hope that helps.

Here's the repository. I planned on publishing it later but I provided source as requested.

回答1:

Have you read the plugin developers documentation?

That page will link to Plugins Cookbook which links to Mojo Developer Cookbook which has The maven project, or the effective pom. and gives you access to org.apache.maven.project.MavenProject object via

/** @parameter default-value="${project}" */
private org.apache.maven.project.MavenProject mavenProject;

Alternatively via Java 5 annotations

@Component
MavenProject project;

You can call getCompileSourceRoots() to get a list of the directories that will be used for compilation.

You will also need to do more reading about how to setup inclusion/exclusions. You can use other plugins as examples of how to do this, e.g. maven-compiler-plugin

If you want to use annotations, it is very important to make sure your pom is configured as per using annotations and that you use annotations at the class level as well. Mixing javadoc annotations might not work.



回答2:

I think the simplest solution would be to define a mojo parameter:

/**
 * @parameter default-value="${project.build.sourceDirectory}"
 * @required
 */
private File sourceDirectory;

or with new annotation based definition:

@Parameter(required = true, defaultValue="${project.build.sourceDirectory}"}
private File sourceDirectory;

which should give your wished result.