Please, what is the most convenient way how to call a Java method within Gradle build script? This method contain functionality I want to use during build; a piece of functionality too complex to be a in-script Groovy method but not enough to command full custom Gradle plugin.
My question is not about running a Java application from Gradle. That would involve forking JVM, and there is no simple way how to publish output back to Gradle and I need that output.
Initially I had my code in src/main/java but it has to be compiled early on to be callable from within Gradle build script.
Then I tried to move the build helper class to a submodule project, a one class submodule, hoping that the submodule would be builded before the main build script is called; in there I put:
buildscript {
dependencies {
classpath 'this.project:build-helper:1.0-SNAPSHOT'
}
}
But the build-helper
subproject is clearly not build first, despite having in in settings.gradle
as first and build fails as the dependency is not recognised. It seems buildscript is evaluated before submodules are built, before anything else. D'oh!
There's two main use cases
Source is in src/main/java
in the current project - Therefore the class does NOT exist when the buildscript classpath is defined
Options:
Use a JavaExec task to run the class in another JVM
Construct a URLClassLoader from sourceSets.main.runtimeClasspath
and load / run the class via the classloader
eg:
task doStuff {
doLast {
URL[] urls = sourceSets.main.runtimeClasspath.files as URL[]
def classloader = new URLClassLoader(urls, null)
Class myClass = classloader.load("foo.bar.MyClass")
def myInstance = myClass.newInstance()
Method method = myClass.getMethod("doStuff")
method.invoke(myInstance)
}
}
Source is in another project. - Therefore the class will exist before the buildscript classpath is defined
In this case you can add the project to the buildscript classpath and invoke it
buildscript {
dependencies {
classpath project(':other-project')
}
}
task doStuff {
doLast {
def myClass = new MyClass()
myClass.doStuff()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With