It is less complex, it´s just like any other
java-project:this.getClass().getResourceAsStream( name )
this.getClass().getResource( name );
The @requiresDependencyResolution is about which dependecies should be
available for this class, based on their scope. -Robert> Date: Sat, 16 Jul 2011
21:25:40 -0700
> Subject: How to load a class in a Mojo?
> From: hilco.wijbe...@gmail.com
> To: users@maven.apache.org
>
> Hi all,
>
> According to [1] you need a custom URLClassLoader and
> @requiresDependencyResolution in order to load a class from the
> classpath. So I have in my Mojo:
>
> /**
> * @goal run
> * @phase generate-sources
> * @requiresDependencyResolution compile (I also tried runtime)
> */
> public class RunMojo extends AbstractMojo {
> :
> public void execute() throws MojoExecutionException {
> :
> try {
> final File rootDir = new File("target/classes");
> if (!rootDir.exists()) throw new IllegalStateException("Does not
> exist.");
> final Deque<File> queue = new LinkedList<File>();
> queue.add(rootDir);
> while (!queue.isEmpty()) {
> final File dir = queue.poll();
> for (final File f : dir.listFiles())
> if (f.isFile()) System.out.println(f); else if
> (f.isDirectory()) queue.add(f);
> }
> final URL targetClasses = new URL("file", null, file.getAbsolutePath());
> System.out.println(targetClasses);
> final URLClassLoader classLoader = new URLClassLoader(new URL[]
> { targetClasses });
> final Class<?> mainClass = classLoader.loadClass("org.example.Main");
> getLog().info("Main.class=" + mainClass);
> } catch (final Exception e) {
> throw new MojoExecutionException(e.getMessage(), e);
> }
> }
> :
> }
>
> This yields a ClassNotFoundException. Note that org.example.Main has
> no dependencies (it's simply an implementation of "Hello World!").
>
> I can see that I made no errors in the URL, Main.class is available
> and where I expect it to be.
>
> What am I doing wrong?
>
> Cheers,
> Hilco
>
> [1] https://cwiki.apache.org/MAVEN/maven-3x-class-loading.html
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscr...@maven.apache.org
> For additional commands, e-mail: users-h...@maven.apache.org
>