fatfatson
fatfatson

Reputation: 885

what's the `this` object in gradle?

with this build.grade:

task hello{
    doLast{
        println'Hello World!'
    }
}

defaultTasks 'hello'
this.buildDir="binin"
project.buildDir="bout"
ext.abc="test abc"

println "buildDir is: ${this.buildDir}"
println "buildDir is: "+project.buildDir
println "project=${project}, ${project.project}, ${this==project} ${this.equals(project)}"
println "this=${this}, ${this.project}, ${this.project.equals(project)}"
println "this.ext, ${this.ext}, ${this.project.ext}, ${this.ext==this.project.ext}"

the output is:

buildDir is: /mnt/e/code/hbg/source/_posts/scripts/bout
buildDir is: /mnt/e/code/hbg/source/_posts/scripts/bout
project=root project 'demo', root project 'demo', false, false
this=root project 'demo', root project 'demo', true
this.ext, org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension@3b77c6e3, org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension@3b77c6e3, true

it shows that this is a Project instance but not the current project, however this.project is project and project.project is alsoproject.

so what's the this object??

when we are writting a build file, aren't we constructing a Project instance? why this is not the current constructing instance?

Upvotes: 2

Views: 199

Answers (2)

Dave L.
Dave L.

Reputation: 9791

An object implementing the Script interface. See here

Generally, a Script object will have a delegate object attached to it. For example, a build script will have a Project instance attached to it, and an initialization script will have a Gradle instance attached to it.

Upvotes: 2

Henry
Henry

Reputation: 43738

this refers to the script itself, which delegates (almost) everything the the current project. Therefore, when you call a method on this, actually the corresponding method of the project is called. The same holds for accessing properties.

But still this is not the same as the project.

Upvotes: 2

Related Questions