10

I have a Gradle build script which has to instantiate a Java class in a Task and call a method on the created object. Currently, I have the following:

apply plugin: 'java'

dependencies {
    compile files("libs/some.library.jar")
}

task A << {

    def obj = new some.library.TestClass()
    obj.doSomething()

}

The problem is that the class some.library.TestClass() is not found. I read this article about how to use Groovy classes in Gradle, but I need my Java class to come from an external JAR file. How can I add a jar to the build source? It seems that the dependencies block doesnt do what I expect it to do. Can anyone give me a hint in the right direction?

0

1 Answer 1

16

The dependency compile files("libs/some.library.jar") is added as a project dependency not as the script dependency itself. What You need to do is to add this dependency in script's classpath scope.

apply plugin: 'java'

buildscript {
   dependencies {
      classpath files("libs/some.library.jar")
   }
}

task A << {
    def obj = new some.library.TestClass()
    obj.doSomething()
}

Now it should work.

Sign up to request clarification or add additional context in comments.

1 Comment

This also works in Android Studio, although you don't need the 'apply plugin' line, which it will complain conflicts with the android plugin, and 'buildscript' needs to be all lower case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.