I want to define and use java class directly in one of my .gradle scripts. Something like
public class Printer {
void print() {
// this compiles and works
java.util.List<String> list = Arrays.asList("1", "2");
for (String s : list) {
System.out.println(s);
}
// this does not compile
list.forEach(s -> System.out.println(s))
}
}
I am trying to force gradle to use java 8 compiler version:
compileJava {
sourceCompatibility = ‘1.8’
}
So (my totally noob) question is - how to switch java version in gradle script itself - and not in the sorce code it is compiling.
You can use Java8 in build script, if JAVA_HOME points jdk1.8.
For example, I created the script in build.gradle.
task useJdk18Feature {
doLast {
[1,2,3,4,5].forEach {
println it
}
}
}
And I ran the following commands, and it results as follows.
$ gradle --version
------------------------------------------------------------
Gradle 2.7-rc-2
------------------------------------------------------------
Build time: 2015-09-05 14:06:15 UTC
Build number: none
Revision: eda1c714012725fdfdffb0c6b8223529b305b3f2
Groovy: 2.3.10
Ant: Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM: 1.8.0_60 (Oracle Corporation 25.60-b23)
OS: Mac OS X 10.10.5 x86_64
$ gradle useJdk18Feature
:useJdk18Feature
1
2
3
4
5
BUILD SUCCESSFUL
Total time: 0.954 secs
From Groovy2.2, you can use Closure as java.util.function.Consumer in java.util.stream.Stream operations. So Closure can be parameter for forEach method.
If you want use java.util.function.Consumer instead of Closure, then use Map as follows.
list.forEach([accept: {s ->
println s
}] as java.util.function.Consumer)