简体   繁体   中英

how to load a jar package in a maven plugin

I have created a maven plugin, the plugin will parse java source code and submit the results to my console.

But now I have a problem, some java classes are written by a third-party or by other groups at my company, then my plugin can't get these classes' structure, fields, method parameter type, method return type etc.

At last, I modified my plugin to run at the package phase, while maven packages the source code, then the plugin can load the jar package and load all the classes in the jar. But now, the classloader doesn't work.

My plugin code can be seen below:

@Mojo(name = "report", threadSafe = true,defaultPhase= LifecyclePhase.PACKAGE)
@Execute(phase =LifecyclePhase.PACKAGE )
public class JavadocMojo extends AbstractMojo {

    @Component
    private MavenProject mavenProject;

    @Override
    public void execute() {

       try {
            File targetDir = new File(mavenProject.getCompileClasspathElements().get(0)).getParentFile();

            Optional<File> optional = Arrays.stream(targetDir.listFiles()).filter(t->t.getName().endsWith(".jar")).findFirst();
            File file = optional.get();
            URLClassLoader urlClassLoader=new URLClassLoader(new URL[]{file.toURI().toURL()},mavenProject.getClass().getClassLoader());


            // the full class name is other project's class of mine
            // this classload cann't load the target class and throws ClassNotFoundException while I'm debug the plugin
            urlClassLoader.loadClass("com.x.y.z.MyClass");
           

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

finally,I resolve the question,this maven plugin can load the classes while running in compile stage or others, thanks.

@Mojo(name = "report", threadSafe = true,defaultPhase= LifecyclePhase.COMPILE,requiresDependencyResolution = ResolutionScope.COMPILE)
@Execute(phase=LifecyclePhase.COMPILE)
public class JavadocMojo extends AbstractMojo {

    @Override
    public void execute() {
            List<String> list = mavenProject.getCompileClasspathElements();
            JarClassLoader jarClassLoader=new JarClassLoader(this.getClass().getClassLoader());
            for(String item: list){
                jarClassLoader.add(new File(item).toURI().toURL());
            }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM