Search code examples
javagradlesource-sets

How to build some java files to one jar using gradle java-plugin?


I want to compile some java files to one jar file with gradle.
The goal is to add them to a jar and check the dependcies of the tests.
Maven should integrate the junit libary.
I also want to apply some kind of filter to test only the files with *Tests.java
The build.gradle file is in the same directory as the src folder.

My file structure(folders or filenames cannot be changed):

src/eu/conflicts/Conflicts.java
src/eu/conflicts/ConflictsTests.java
src/eu/utils/BuggyUtils.java
src/eu/utils/BuggyUtilsTests.java

After running gradle -b build.gradle jar I got the error message: Could not find the main method

apply plugin: 'java'

repositories {
   mavenCentral()
}

dependencies {
   testCompile 'junit:junit:4.12'
}

sourceSets {
   main {
      conflicts {
         srcDir = 'src/eu/conflicts'
      }
      utils {
         srcDir = 'src/eu/utils'
      }
   }

   test {
      conflicts {
         srcDir = 'src/eu/conflicts'
      }

      utils {
         srcDir = 'src/eu/utils'
      }
   }
}

jar {
   baseName = 'xy'
   version = '0.1'
   manifest {
      attributes("Implementation-Title": "xy",
                 "Implementation-Version": 0.1)
   }
}

Solution

  • Your source sets definition is incorrect. Java plugin only supports java and resources source types within a source set. Each source set can have an arbitrary name. If you name your source set main it will customise the one used by convention by the jar task. So:

    apply plugin: 'java'
    
    sourceSets {
      main {
        java {
          srcDir 'src'
          exclude '**/*Tests.java'
        }
      }
    
      test {
        java {
          srcDir 'src'
          include '**/*Tests.java'
        }
      }
    }