How to refer to classes on the buildscript classpath in an applied script


(Matt Khan) #1

I add some dependencies (containing our plugins) to the buildscript classpath. I then want to refer to some class I’ve added in the script and set some ‘ext’ property. For example, lets say I just want to get a reference to ‘SomeEnum.values()’ and ‘SomeEnum’ is on my classpath.

As far as I can see, this does not work when the code is shifted to a gradle script that is applied and I can’t see why this would be so. For example, this works;

// build.gradle
ext {
    someValues = com.mycomponent.SomeEnum.values()
}
  someValues.each {
     // do something with it
}

but this does not

// build.gradle
apply from: projects.gradle
  // projects.gradle
ext {
    someValues = com.mycomponent.SomeEnum.values()
}
  someValues.each {
     // do something with it
}

The latter blows with

* What went wrong:
A problem occurred evaluating script.
> cannot get property 'com' on extra properties extension as it does not exist

(Peter Niederwieser) #2

Officially, each build script needs to declare its build script dependencies on its own. In the current implementation, a child build script can also see the parent script’s dependencies, but this isn’t the case for applied build scripts.


(detelinyordanov) #3

It seems to be designed that way, the build script’s ClassLoader is used only for project’s build script and not for any other script, see AbstractProject.beforeCompile


(Matt Khan) #4

what is a “child build script” exactly?

This seems slightly counterintuitive and/or inconsistent though given that the applied script references things (plugins) that only exist by virtue of the classpath specified in the applying script.

In the current implementation

does this imply the implementation is changing?


(Peter Niederwieser) #5

A child build script is the build script of a child (i.e. sub) project.

does this imply the implementation is changing?

It means that the inheritance behavior isn’t a guaranteed feature.


Making a jar available to all scripts classpaths (even applied scripts)
(Matt Khan) #6

OK thanks. This implies that this should work then (but it doesn’t) or are you saying that inheritence only applied if it is within the same script?

// build.gradle start
buildscript {
    // add something to classpath
}
  // do some root project configuration
  apply from: project.gradle
  // build.gradle end
  // project.gradle start
  project('projectA') {
    ext {
        someValues = com.mycompany.SomeEnum.values()
    }
}
// project.gradle end

(Peter Niederwieser) #7

It won’t work because it’s an applied build script, but the class path is only inherited by child build scripts (i.e. build scripts of child projects).