Enforcing targetCompatibility when compiling Java code with the Groovy plugin


(Andres Almiray) #1

As far as I understand from the ‘GroovyCompile’ documentation both ‘sourceCompatibility’ and ‘targetCompatibility’ are passed directly to the Java compile options. However I’m unable to obtain the desired results. I’ve setup a trivial project (1 Java class) in the following manner

.
├── build.gradle
├── gradle.properties
└── src
    └── main
        └── java
            └── sample
                └── Foo.java

With the following build file

apply plugin: 'groovy'
  repositories {
    jcenter()
}
  sourceCompatibility = 1.7
targetCompatibility = 1.7
  dependencies {
    testCompile 'org.codehaus.groovy:groovy-all:2.3.3'
    testCompile 'org.spockframework:spock-core:0.7-groovy-2.0'
}

Please note that the usage of the ‘groovy’ plugin is only for tests. Now, compiling with

------------------------------------------------------------
Gradle 2.0
------------------------------------------------------------
  Build time:
 2014-07-01 07:45:34 UTC
Build number: none
Revision:
   b6ead6fa452dfdadec484059191eb641d817226c
  Groovy:
     2.3.3
Ant:
        Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM:
        1.8.0_05 (Oracle Corporation 25.5-b02)
OS:
         Mac OS X 10.9.3 x86_64

and running ‘javap -v’ on the compiled class results in

Classfile /private/tmp/test/build/classes/main/sample/Foo.class
  Last modified Jul 3, 2014; size 248 bytes
  MD5 checksum deff50e85bfac55381b050f47c9050dc
  Compiled from "Foo.java"
public class sample.Foo
  SourceFile: "Foo.java"
  minor version: 0
  major version: 52
 ...

Which means the target bytecode is set to 1.8 instead of the desired 1.7 :frowning:

UPDATE: I’ve found http://stackoverflow.com/questions/21028438/gradle-sourcecompatibility-1-6-does-not-seem-to-create-1-6-byte-code which pretty much describes the same problem. The workaround is to place the following snippet in the test build

tasks.withType(JavaCompile) {
    sourceCompatibility = '1.7'
    targetCompatibility = '1.7'
}

So. Is the documentation about sourceCompatibility/targetCompatibility wrong? Should the “workaround” be promoted to “the right way to do it” ? Are these properties simple being ignored?

PS: got the same results by applying the ‘java’ plugin alone, so I think this boils down to the compiler infrastructure, not just the Groovy compiler.


(Luke Daley) #2

Would you mind posting a project on GitHub that we can use to verify?


(Andres Almiray) #3

I’m stumped. Re-created the simple project and tested it before uploading to Github. Setting up the compatibility flags like the documentation explains does the trick. I’ll triple checking again and let you know.