How to add java source to gradle buildscript classpath?

I have a Java class that I want to call 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 simply returns a string.

The layout of the project is as follows:

 . β”œβ”€β”€ build.gradle └── src └── main └── java └── com └── example └── MyClass.java 

I understand that I need to add the class to the script assembly dependency, otherwise the import is not valid, but I do not understand how I can add the project source as a dependency for the script assembly, I tried the following:

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

I can not 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 to add MyClass to build script dependency?

+5
source share
1 answer

There are two ways to do this.

  • If your Java code is small, you can just turn it into groovy and include it in a gradle script.

  • If your code is quite large and requires several classes, the preferred option is to use implicit [buildSrc]. You can create classes in buildSrc / src / main / java, and these classes will be compiled and placed in the buildscript class path and will be available for use during gradle script.

Project sources (class, test classes, resources) are not available during script build. Since this will lead to a circular dependency, since you need your assembly to compile the source, but the assembly requires a 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/

+6
source

Source: https://habr.com/ru/post/1212665/


All Articles