How to use a class from a dependency in my build script?


(Mike M) #1

How do I use a class in my build.gradle script, which I’ve included as a dependency?

I need to call a library function to decrypt a password. I have this library checked into my project under a subdirectory, like so:

project/
    build.gradle
    build_lib/
        bar-1.1.jar

build.gradle

import com.example.foo.FooBar

buildscript {
    repositories {
        mavenLocal()
        flatDir name: 'build_lib', dirs: System.getProperty("user.dir") + '/build_lib'
        maven{
            url = "http://dc1artifctry01:8081/artifactory/releases"
            credentials {
                username System.getProperty('user.name')
                password FooBar.getThePassword()
            }
        }
    }
    dependencies {
        classpath "com.example.foo:bar:1.1"
    }
}

However, when I run the build, I get this error:

Error initializing classpath: No such property: FooBar for class: org.gradle.api.internal.artifacts.repositories.DefaultPasswordCredentials_Decorated

(Mike M) #2

It turns out I was misunderstanding when and how classes become available in the build script.

When gradle runs a build, it basically takes everything inside buildscript and runs it first, as though it were a separate build, then it runs the rest of build.gradle. As a result, the classes put onto the classpath via the dependencies declared in buildscript can only be accessed by code outside the buildscript block.

Only core gradle classes/tasks/etc. are available inside the buildscript block.