Frage

In my plugin I need to execute static bootstrapping method from an external JAR to perform an analysis. Currently I call it directly from code with MutationCoverageReport.main(arg), but this forces me to create a compile time dependency in my plugin which is hard to modify (choose a different JAR version) when executing the plugin.

I would like to call it using reflection and found some examples in Gradle code like WorkerProcessBuilder or JavaExecHandleBuilder. Nevertheless they are in org.gradle.process.internal package and I'm not sure if it is recommended to use it from the external plugin.

Question. What is the recommended way for Gradle plugin to run arbitrary Java method from external class with specified classpath?

Btw, I would prefer to not use an Ant task as it is a separate project and another layer of abstraction with its potential bugs and limitations.

War es hilfreich?

Lösung

There are a couple of approaches that you could take to invoke a main method in an external Jar:

  1. Use a JavaExec task, or a custom task that leverages the project.javaexec method.
  2. Put the external Jar on the build script class path and invoke its main method directly or reflectively from a custom task. The external Jar could be a transitive dependency of the plugin Jar. Alternatively, it could be left to the user to put the external Jar on the build script class path (buildscript { dependencies { classpath ... } }).
  3. Write a custom task that creates its own class loader, puts the external Jar on it, and calls its main method reflectively.

The first approach will run the code in a separate JVM, which is often desirable. The second and third approaches can also invoke methods other than main methods. In the first or third approach, the plugin could add a configuration which allows the user to supply the external Jar by declaring a dependency in the dependencies block. (The plugin could provide a default dependency.) This is what many built-in Gradle plugins do, for example the code quality plugins (checkstyle etc.). You may want to study their code to get some inspiration.

External plugins should only use classes from Gradle's public API, that is classes that are documented in the Javadoc or Groovydoc. (Not all internal classes have internal in the package name.)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top