JDK18 features


Insert image description here

JAVA18 overview

Java 18 was officially released on March 22, 2022. Java 18 is not a long-term support version. This update brings a total of 9 new features.

official address

image.png

1. Default UTF-8 character encoding

JDK has always supported UTF-8 character encoding. This time, UTF-8 is set as the default encoding. That is, without any specification, all JDK APIs that require encoding use UTF-8 encoding by default. This can avoid coding problems caused by different systems, different regions, and different environments.

2. Simple Web Server

Provide a simple web service in JDK18. That is, a command is provided in the bin directory jwebserver. Run this command to start a 简单的、最小的static web server. It does not support CGI and Servlets, so the best usage scenarios are for testing, education, demonstration and other needs.

image.png

3.Enhancement of JavaDoc

New enhancements to JavaDoc have been added in Java 18. Although previous versions already provided the ability to add code snippets to JavaDoc, they did not provide support for highlighting. Features provided in Java18

/**
 * JavaDoc特性讲解
 *  {@snippet :
 *      if(v.isPresent()){
 *          System.out.println("Hello ... ")
 *      }
 *  }
 */
public class Test01 {
    
    

    /**
     * 正则高亮:
     * {@snippet :
     *   public static void main(String... args) {
     *       for (var arg : args) {                 // @highlight region regex = "\barg\b"
     *           if (!arg.isBlank()) {
     *               System.out.println(arg);
     *           }
     *       }                                      // @end
     *      }
     *   }
     */
    public static void main(String[] args) {
    
    
        System.out.println(Charset.defaultCharset());
        System.out.println("波哥....");
    }

    /**
     * 两数求和:
     * {@snippet :
     *   public Integer add(int a,int b){
     *      System.out.println("add ..."); // @replace regex='".*"' replacement="..."
     *      return a + b;
     *   }
     * }
     */
    public Integer add(int a,int b){
    
    
        System.out.println("add ...");
        return a + b ;
    }
}

image.png

image.png

4. New features of reflection function

Java 18 improves the implementation logic of java.lang.reflect.Method and Constructor to make them perform better and faster. This change will not change the relevant API, which means that you can experience better reflection performance without changing the reflection-related code during development.

OpenJDK officially provides the reflection performance benchmark results of the new and old implementations.

image.png

5.Vector API (three incubations)

A new API for vector calculations is introduced in Java 16, which can be reliably compiled to supported CPU architectures at runtime, thereby achieving better computing capabilities. Vector API performance has been improved in Java 17, with enhanced functions such as character operations and conversion between byte vectors and Boolean arrays. Its performance will continue to be optimized now in JDK 18.

6. Internet address resolution SPI

Define a Service Provider Interface (SPI) for hostname and address resolution so that java.net.InetAddressresolvers other than the platform's built-in resolvers can be used.

    public static void main(String[] args) throws Exception {
    
    
        InetAddress inetAddress = InetAddress.getByName("cart.msb.com");
        System.out.println(inetAddress.getHostAddress());
    }

7. External functions and memory API (secondary incubation)

The new API allows Java developers to interact with code and data outside the JVM by calling external functions and calling native libraries without using JNI.

This is an incubation feature; it needs to be added --add-modules jdk.incubator.foreignto compile and run Java code, and Java 18 improves the related API to make it easier to use.

8.switch expression

Since Java 17, improvements to Switch have been underway. JEP 406 of Java 17 has enhanced Switch expressions to reduce the amount of code.

Here are a few examples:

// JDK 17 以前
static String formatter(Object o) {
    
    
    String formatted = "unknown";
    if (o instanceof Integer i) {
    
    
        formatted = String.format("int %d", i);
    } else if (o instanceof Long l) {
    
    
        formatted = String.format("long %d", l);
    } else if (o instanceof Double d) {
    
    
        formatted = String.format("double %f", d);
    } else if (o instanceof String s) {
    
    
        formatted = String.format("String %s", s);
    }
    return formatted;
}

After Java 17, it can be improved by the following writing method

// JDK 17 之后
static String formatterPatternSwitch(Object o) {
    
    
    return switch (o) {
    
    
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> o.toString();
    };
}

switch can be nullcombined with:

static void testFooBar(String s) {
    
    
    switch (s) {
    
    
        case null         -> System.out.println("Oops");
        case "Foo", "Bar" -> System.out.println("Great");
        default           -> System.out.println("Ok");
    }
}

Complex expressions can be added to case:

static void testTriangle(Shape s) {
    
    
    switch (s) {
    
    
        case Triangle t && (t.calculateArea() > 100) ->
            System.out.println("Large triangle");
        default ->
            System.out.println("A shape, possibly a small triangle");
    }
}

Type judgment can be performed in case

sealed interface S permits A, B, C {
    
    }
final class A implements S {
    
    }
final class B implements S {
    
    }
record C(int i) implements S {
    
    }  // Implicitly final

static int testSealedExhaustive(S s) {
    
    
    return switch (s) {
    
    
        case A a -> 1;
        case B b -> 2;
        case C c -> 3;
    };
}

Guess you like

Origin blog.csdn.net/qq_28314431/article/details/132950697