Let’s start by acknowledging that Java 8 was a milestone release that most Java programmers recognize, most notably Streams & Lambda, which made Functional Programming possible and reinvigorated Java. Even though Oracle no longer supports Java 8 updates, cloud vendors are still actively supporting them. The site is adoptopenjdk.net/, which allows Java 8 to continue for a very long time.

At present, many students have not switched to the later version of Java 8 in their daily development. Therefore, in this article, we plan to write a feature of the post-Java 8 era, which is mainly oriented towards development and does not involve GC, Compiler, Java Module, Platform, etc. If explained one by one, the estimate is very long article, of course, the follow-up can write another article introduction. The following features will affect our everyday coding.

Considering that Java 13 will be released soon, the version coverage will be from 9 to 13. At the same time, the way Java is released will be changed. Some features were introduced in the preview version, and a lot of enhancements and improvements have been made after receiving feedback. You can think of it as a hodgepodge of features after the Java 8 release. The references come from official Features and PluralSight’s introduction to Java features for each release.

Var keyword (Local Variable Type Inference) local-variable Type Inference

Java supports generics, but if the type is very long and you’re not particularly concerned, you can use the var keyword to keep your code very concise. Java ides support VAR very well without worrying about code prompts and so on.

Map<String, List<Map<String,Object>>>  store = new ConcurrentHashMap<String, List<Map<String,Object>>>();        Map<String, List<Map<String,Object>>>  store = new ConcurrentHashMap<>();        Map<String, List<Map<String,Object>>>  store = new ConcurrentHashMap<String, List<Map<String,Object>>>();  //lambda
  BiFunction<String, String, String> function1 = (var s1, var s2) -> s1 + s2;
        System.out.println(function1.apply(text1, text2));Copy the code

Copy the confd file to the bin directory and start confd

sudo cp bin/confd /usr/local/bin
confdCopy the code

There are some minor limitations to the actual use, such as the null assignment problem, but these are not a problem to use immediately.

ProcessHandle

Although we rarely call system commands in Java, we do occasionally use them, of course, in ProcessBuilder. There is also the enhanced ProcessHandle, which can learn some information about other processes, such as getting all processes, the command to start a process, the start time, and so on.

ProcessHandle ph =  ProcessHandle.of(89810).get();
System.out.println(ph.info());Copy the code

Collection factory methods

Create ArrayList, HashSet, new method, old fashioned method, factory method.

Set<Integer> ints = Set.of(1, 2, 3);
List<String> strings = List.of("first"."second");Copy the code

New API for the String class

I can’t list them all here, but I’ll mention a few important ones that won’t require third-party StringUtils. Repeat, isEmpty, isBlank, strip, lines, indent, Transform, trimIndent, formatted, etc

2 support HTTP

Of course, if you use OkHTTP 3 that’s fine, but if you don’t want to introduce other development packages, Java already supports HTTP 2 and the code is pretty much the same, both synchronous and asynchronous of course.

 HttpClient client = HttpClient.newHttpClient();
        HttpRequest req =
                HttpRequest.newBuilder(URI.create("https://httpbin.org/ip"))
                        .header("User-Agent"."Java")
                        .GET()
                        .build();
        HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
        System.out.println(resp.body());Copy the code

Text Block(JDK 13)

In the previous version, you had a big chunk of text, and you had to convert the double quotation marks, which were very unreadable, like this:

String jsonText = “{“id”: 1, “nick”: “leijuan”}”;

New method text block:

//language=json
  String cleanJsonText = """{"id": 1,"nick":"leijuan"}""";Copy the code

Much easier, you can write code without worrying about double quotes conversion, copy sharing conversion, etc. Wait, why did you add //language=json in front of cleanJsonText? This is a feature of IntelliJ IDEA, your text block still has semantics, such as a paragraph of HMTL, JSON, SQL, etc., after adding this, immediately code prompt. Most people I don’t tell 🙂

One small feature of the Text block is basic template support. You introduce context variables in the text block. Just call %s and formatted.

    //language=html
    String textBlock = """ color: green">Hello %s</span>""";
    System.out.println(textBlock.formatted(nick));Copy the code

The Switch ascension

Arrow Labels

Insert the “->” switch arrow, no need to write so many breaks, the code is as follows:

  //legacy
    switch (DayOfWeek.FRIDAY) {        case MONDAY: {
            System.out.println(1);            break;
        }        case WEDNESDAY: {
            System.out.println(2);            break;
        }        default: {
            System.out.println("Unknown");
        }
    }    //Arrow labels
    switch (DayOfWeek.FRIDAY) {        case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);        case TUESDAY -> System.out.println(7);        case THURSDAY, SATURDAY -> System.out.println(8);        case WEDNESDAY -> System.out.println(9);
    }Copy the code

Switch Expressions

The switch can return a value as follows:

    //Yielding a value
    int i2 = switch (DayOfWeek.FRIDAY) {        case MONDAY, FRIDAY, SUNDAY -> 6;        case TUESDAY -> 7;        case THURSDAY, SATURDAY -> 8;        caseWEDNESDAY -> 9; default -> { yield 10; }};Copy the code

The yield keyword represents the return value of the switch expression.

I want to use these features right away

What you have said is very good, but we are still in Java 8 environment online, what is the use? Just looking around. Don’t worry, someone else has figured it out. Github.com/bsideup/jab… This is the project that supports transparent compilation of JDK 12+ syntax features to Java 8 VMS, meaning that you can now run Java 8 with these syntax features without any problems, so the above features can be used even in Java 8 environments.

How to use it? Very simple.

First download the latest JDK, such as JDK 13, and then add jabel-java-plugin to the dependencies

<dependency> <groupId>com.github.bsideup.jabel</groupId> <artifactId>jabel-javac-plugin</artifactId> The < version > 0.2.0 < / version > < / dependency >Copy the code

Then adjust maven’s Compiler Plugin to set source to the Java version you want, such as 13, and Target and Release to 8. IntelliJ IDEA is automatically recognized and no adjustments are required.

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> The < version > 3.8.1 < / version > < configuration > <source> 13 < /source>
                    <target>8</target>
                    <release>8</release>
                </configuration></plugin>Copy the code

Then you can have fun using the features described.

conclusion

If there are some features that are not sorted out, and very useful, we give feedback, such as API adjustment, etc., for the convenience of subsequent students for reference.

️ Author of this article: Middleware brother

The original link

This article is the original content of the cloud habitat community, shall not be reproduced without permission.