Class pathes in gradle script

i’ve tried to use postgresql in my script, eventually i’ve found a SO post that uses GroovyObject.class.classLoader that loads the class path from configuration that is predefined and it works.

just defining:

buildscript{
    repositories{
        jcenter()
    }   
    dependencies{
        classpath 'postgresql:postgresql:9.1-901-1.jdbc4'
        classpath group: 'commons-codec', name: 'commons-codec', version: '1.10'
    }   
}

for some reason doesn’t do the trick and the line:

def sql = Sql.newInstance(url, props, driver)

fails claiming it can’t find the driver.
using this code i can see the script’s class path does not contain the postgresql jar:
URLClassLoader loadert = this.class.classLoader loadert.getURLs().each { println("*** ${it}") }
just the compiled temp dir for the compiled groovy script.
but if i add in my script:
import org.apache.commons.codec.net.* URLCodec c = new URLCodec(); println(c.encode("http://myurl.com","utf-8"))
it does print it, so it IS in the classpath OR i’m somehow referring to the wrong classpath when printing.
so my questions are:

  1. how come i don’t see any of grrovy’s\java classes that are imported by default when gradle starts ?
  2. why do i see only the script own classes in the class path and how come i can call code that is NOT in the current classloader classpath ?
  3. if i CAN access those classes in buildScript.classpath from my script, why does groov.sql.Sql can’t find the postgresql ? why if i import it explicitly it’s found, could be that the groovy.sql.Sql takes like me the wrong classloader reference ?

Hey,

the problem is indeed a classloading problem with jdbc. I think Sql will only let you access drivers which have been loaded by the calling class’ classloader. In the build script, the caller to Sql isn’t actually the build script, it is Groovy. So, you need to load the driver in the same classloader as Groovy. That’s why you currently have to use this workaround you mentioned when using jdbc directly in Gradle build scripts.

yes so i’ve noticed that the default class path of the script is ONLY the comiled script, petty i can’t change the way DriverManager does it’s loading which would save lots of headache, damn reflection…
10x for the explanation.