Wednesday, February 5, 2020

Java 13 with Gradle 6

0 lượt xem comment 0 comments

Java still used for many digital product companies even today. Currently, Java is on version 13. Today I want to show how to use JDK13 with Gradle6. JDK13 has some improvements on GC(as usual), minor new methods for Strings and IO and there are 2 interesting new Experimental Features. So let's get started.


Gradle Project

Let's take a look at the build.gradle file.

buildscript {
repositories {
maven {
url 'https://plugins.gradle.org/m2/'
}
}
}
apply plugin: 'application'
apply plugin: 'java'
compileJava {
options.compilerArgs += ["--enable-preview"]
}
test {
jvmArgs '--enable-preview'
useJUnitPlatform()
}
sourceCompatibility = 13
targetCompatibility = 13
mainClassName = 'Main'
repositories {
mavenCentral()
maven { url 'https://oss.sonatype.org/content/groups/public/' }
}
dependencies {
implementation 'org.slf4j:slf4j-api:1.7.25'
implementation 'org.slf4j:slf4j-jdk14:1.7.25'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.5.2'
}
application {
applicationDefaultJvmArgs = ["--enable-preview"]
}
view raw build.gradle hosted with ❤ by GitHub
Besides using the Java plugin. We need to set the source code compatibility and target to 13. We also need to pass additional parameters for compile, testing and running in order to enable experimental features. Now we can go to the new Experimental features in Java 13.

Java 13 Code

import java.util.Random;
public class Main{
public static void main(String args[]){
formating();
switchfun();
}
private static void formating(){
String jsonBlock = """
{
greeting: "Hello",
audience: "World",
punctuation: "!"
}
""";
System.out.println(jsonBlock);
}
private static void switchfun(){
boolean result = switch (new Random().nextInt() % 1){
case 0 -> {
System.out.println("Bool true");
yield true;
}
case 1 -> {
System.out.println("Bool false");
yield false;
}
default -> {
System.out.println("DEFAULT");
yield false;
}
};
System.out.println(result);
}
}
view raw Main.java hosted with ❤ by GitHub

So here we have 2 features. First, we have a multi-line string with """ and then we can pass a Json object without annoying scaping "\" like we had to do it before. The other cool feature is that we can use switch statements directly in a variable which makes the switch more similar to a pattern matcher.

Here is the complete code on my GitHub.

Cheers,
Diego Pacheco
Tags: code,

comment 0 comments

Chuyên mục văn hoá giải trí của VnExpress

.

© 2017 www.blogthuthuatwin10.com

Tầng 5, Tòa nhà FPT Cầu Giấy, phố Duy Tân, Phường Dịch Vọng Hậu, Quận Cầu Giấy, Hà Nội
Email: nguyenanhtuan2401@gmail.com
Điện thoại: 0908 562 750 ext 4548; Liên hệ quảng cáo: 4567.