How to add java source onto gradle buildscript cla

2019-06-22 16:41发布

问题:

I have a Java class that I want to invoke from my gradle build script:

buildscript {
    dependencies {
        // This is the part I can't figure out...
        classpath files("src/main/java/com/example")
    }
}

import com.example.MyClass

task runner(dependsOn: 'classes') << {
        def text = com.example.MyClass.doIt()
        println text
}

The doIt() method just returns a String.

Project layout looks like:

.
├── build.gradle
└── src
    └── main
        └── java
            └── com
                └── example
                    └── MyClass.java

I understand that I need to have the class added to the build script dependency, otherwise the import is not valid, but I don't understand how I can add the project source as a dependency for the build script. I've tried the following:

classpath project
classpath rootProject
classpath project(":gradle-test")
classpath files("src/main/java/com/example")

I can't get around

> startup failed:
  build file '/Users/jameselsey/development/james-projects/gradle-test/build.gradle': 8: unable to resolve class com.example.MyClass
   @ line 8, column 1.
     import com.example.MyClass
     ^

  1 error

How do I add MyClass to the build script dependency?

回答1:

You could achieve this using two ways.

  1. If your Java code is small then you could simply turn it into groovy and include it in the gradle script.

  2. If your code is rather large and requires multiple classes, preferred option would be to use the implicit [buildSrc] You can create classes under buildSrc/src/main/java and those classes will get compiled and placed in the buildscript classpath and will be available to use during gradle script.

The project sources (class,test classes, resources) are not available during the build script. As this would introduce a cyclic dependency, since you need your build to compile the source, yet the build needs the class to execute.

Gradle Documentation: http://gradle.org/docs/current/userguide/organizing_build_logic.html#sec:build_sources

Example: https://zeroturnaround.com/rebellabs/using-buildsrc-for-custom-logic-in-gradle-builds/



标签: gradle