Search code examples
javagradlegradle-2

How do you add a source set to a Java project in gradle 2.1?


How do you add a source set to a Java project in gradle 2.1?

I've read the docs on the Java Plugin and SourceSetOutput and a few other SO threads and I'm still struggling to figure out how it works.

I created a simple build script to test my understanding. Based on Section 23.7.2, example 23.5 of the User Guide, it appears I can create a sourceSet by doing:

sourceSets {
   generated
}

In section 23.4. Project layout seems to imply that this all I need to do because my source set follows the gradle convention. Code to be included in the source set is in src/generated/java/packagename. and will be automatically added to the classpath. Based on the symbol not found errors I'm getting from code that uses code defined in the generated source set, I assume that this incorrect and something else needs to be done. What do I need to do?

Here's my setup:

build.gradle

apply plugin: 'java'
apply plugin: 'application'

mainClassName = "tester.Test"

sourceSets {
    generated
}

File structure

tester/
├── build
│   ├── classes
│   │   └── main
│   ├── dependency-cache
│   └── tmp
│       └── compileJava
├── build.gradle
└── src
    ├── generated
    │   └── java
    │       └── tester
    │           └── Boom.java
    └── main
        └── java
            └── tester
                └── Test.java

Boom.java

package tester;

class Boom {
   String sound;

   public Boom (String s){
      sound = s;
   }
}

Test.java

package tester;

class Test {
   public static void main(String[] args) {
      Boom b = new Boom("KABOOM");

      System.out.println("I've run");
      System.out.println(b.sound);
   }
}

Solution

  • You need to modify build.gradle in the following way:

    sourceSets {
        generated
        main {
            compileClasspath += generated.output  // adds the sourceSet to the compileClassPath
            runtimeClasspath += generated.output  // adds the sourceSet to the runtimeClasspath
        }
    }
    
    project.run.classpath += sourceSets.generated.output //add the sourceSet to project class path
    

    Remember that adding new source set is something different from having compiled source set in the classpath.

    The line below the source sets is necessary for run task to work.