Noel Yap
Noel Yap

Reputation: 19788

How to access Gradle `project` from `buildSrc`?

I have the following in buildSrc:

class MyClass {
    def doSomething() {
        final familyMembers = project.configurations['compile'].allDependencies.collect { dep ->
            dep.name
        }
    }

but when I try to use it in build.gradle:

task 'do-something' << {
    final myObject = new MyClass()
    myObject.doSomething()
}

the following error is emitted:

* What went wrong:
Execution failed for task ':my-project:do-something'.
> No such property: project for class: MyClass

How do I get project to be visible within MyClass?

Upvotes: 3

Views: 1035

Answers (1)

akhikhl
akhikhl

Reputation: 2578

You'll have to pass project as a parameter to MyClass.

For example, declare a constructor and a member variable:

    class MyClass {
        private Project project

        MyClass(Project project) {
          this.project = project
        }

        def doSomething() {
            final familyMembers = project.configurations['compile'].allDependencies.collect { dep ->
                dep.name
            }
        }

and then use it from your project as such:

    task 'do-something' << {
        final myObject = new MyClass(project)
        myObject.doSomething()
    }

Upvotes: 4

Related Questions