I have a Java compile task to create my project. In another task I want to use (import?) these classes to get some information which I need during task execution. How can I do this in Gradle?
The buildscript classpath is defined before the JavaCompile
task runs so you’ll need to use a Classloader.
Eg:
apply plugin: 'java'
task useMyCompiledClasses {
dependsOn compileJava
doLast {
URL[] urls = sourceSets.main.runtimeClasspath.files.collect { it.toURI().toURL() } as URL[]
def classloader = new java.net.URLClassloader(urls, null)
Class type = classloader.loadClass('com.foo.MyClass')
def myInstance = type.newInstance()
myInstance.doStuff()
}
}
2 Likes
This is exact what I was looking for. Thanks!
However I was getting an error “unable to resolve class java.net.URLClassloader” (the letter “L” is in lower case). Correct is URLClassLoader
At the end my code look like this:
task encrypt {
dependsOn compileJava
doLast {
URL[] urls = sourceSets.main.runtimeClasspath.files.collect { it.toURI().toURL() } as URL[]
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
def classloader = new URLClassLoader(urls, sysClassLoader)
Class type = classloader.loadClass('br.com.mycompany.EncryptMaster')
def myInstance = type.newInstance()
def result = myInstance.stringEncryptor().encrypt("Testing Cryptography")
println "Result: " + result
}
}
1 Like