编程知识 cdmana.com

What are the new features of Java 11?

Java 11 Is from Java 8 Another since LTS edition , It is currently the most used in the world LTS One of the versions . Today we are going to Java 9 To Java 17 In this series of articles, learn about... For ordinary developers Java 11.

character string API enhance

stay Java 11 in , in the light of String The operation of is further strengthened . Avoid introducing additional... In very common scenarios 、 complex API.

isBlank()

Used to determine whether the string is an empty character "" perhaps trim() after (" ") Is an empty character :

String blankStr = " ";
// true
boolean trueVal = blankStr.isBlank();

lines()

String a string according to the line terminator ( A newline \n Or carriage return \r) Segmentation , And split into Stream flow :

String newStr = "Hello Java 11 \n felord.cn \r 2021-09-28";

Stream<String> lines = newStr.lines();
lines.forEach(System.out::println);

The final output :

Hello Java 11
felord.cn
2021-09-28

strip()

Remove the... Before and after the string “ Full and half angles ” Blank character :

String str = "HELLO\u3000";
// str = 6
System.out.println("str = " + str.length());
// trim = 6
System.out.println("trim = " + str.trim().length());
// strip = 5
System.out.println("strip = " + str.strip().length());

I can't help remembering trim() Method , The difference can also be seen from the above ,trim() Can only remove Half angle Blank character .

strip() There are two variants of the method ,stripLeading() Used to remove the front full width and half width white space ;stripTrailing() Used to remove the full width and half width space of the tail .

repeat(n)

Repeat the contents of the concatenated string a given number of times :

String str = "HELLO";
// Null character
String empty = str.repeat(0);
// HELLO
String repeatOne = str.repeat(1);
// HELLOHELLO
String repeatTwo = str.repeat(2);

Set to array of corresponding type

Before, it was troublesome to convert the set to the corresponding array , Or use iteration ; Either use Stream flow , Now you can do this :

List<String> sampleList = Arrays.asList("felord.cn", "java 11");
// array = {"felord.cn", "java 11"};
String[] array = sampleList.toArray(String[]::new);

Assertion negation

java.util.function.Predicate It is a very common assertion predicate function . In the past, we had to resort to ! Symbol , here we are Java 11 We can use its static method not To achieve , This makes the semantics clearer :

List<String> sampleList = Arrays.asList("felord.cn", "java 11","jack");
// [jack]
List<String> result = sampleList.stream()
// Filtering to j Starting string
.filter(s -> s.startsWith("j"))
// At the same time, it does not include 11 String
.filter(Predicate.not(s -> s.contains("11")))
.collect(Collectors.toList());

Actually Predicate The original version also provided a default method for negation :

default Predicate<T> negate() {
return (t) -> !test(t);
}

I am here. The articles It has also been used for combination verification in , The scenarios of these two methods are different .

var Can be used to modify Lambda local variable

stay Java 10 Introduced in var For type inference . stay Java 10 It cannot be used to decorate Lambda The input parameters of the expression , Actually, for a Lambda For an expression, the type of its input parameter can be inferred from the context . Take the example above ,s -> s.startsWith("j") Medium s It must be a string type , So in Java 11 in var Can be used to modify Lambda local variable :

List<String> result = sampleList.stream()
// Filtering to j Starting string
.filter((@NotNull var s) -> s.startsWith("j"))
// At the same time, it does not include 11 String
.filter(Predicate.not((@NotNull var s) -> s.contains("11")))
.collect(Collectors.toList());

If we don't declare var There is no way to add... To the input parameters @NotNull annotation .

It is more convenient to read and write the string content in the file

Java 11 It is easier to read and write string contents from files , We can go through Files New static methods provided by tool classes readString and writeString Read and write the string contents of the file respectively , It's always troublesome to put it before , Especially for IO For unfamiliar students . Now it's done in a few lines :

String dir= "C://yourDir";
// write file
Path path = Files.writeString(Files.createTempFile(dir, "hello", ".txt"), "hello java 11");
// Read the file
String fileContent = Files.readString(path);

Access control rules for nested classes

stay Java 11 Before , It is feasible for inner nested classes to access private properties and methods of outer classes :

public class Outer {
private int outerInt;

class Inner {
public void printOuterField() {
System.out.println("Outer field = " + outerInt);
}
}
}

But if you reflect API If you implement the internal class to access the private properties and methods of the external class, you will throw IllegalStateException abnormal .Java 11 Fixed reflection inaccessible problem .

JVM Access rules do not allow private access between nested classes . We can access it in the normal way because JVM Implicitly created... For us at compile time Bridge method .Java 11 Two new properties are introduced in : A place called NestMembers Properties of , Used to identify other known static nest member ; The other is each nest Members contain NestHost attribute , Used to identify its nest Host class . The host relationship between the two sides is mapped at compile time , There is no need for bridging .

HttpClient Support HTTP2

HttpClient here we are Java 11 I started to support HTTP2, The bottom layer is greatly optimized , And now fully supports asynchronous non blocking .

HttpClient The name of the bag is jdk.incubator.http Change it to java.net.http.

Other

Java 11 in , There are other features and optimizations , For example, the introduction of ZGC, Support support TLS 1.3 agreement , Dynamic call is introduced (invokedynamic) Mechanism , In addition, the original commercial version JFR Open source integration has also been carried out . At the beginning of the year Java Ecological survey data show that Java 11 The number of users has increased significantly , It has become one of the mainstream version choices .

The author of this article : Small fat man of minong ,
Link to the original text :https://mp.weixin.qq.com/s/dv4v1pAar9nqEUSK1YcLvg
The copyright belongs to the author , Please indicate the author of the reprint 、 original text 、 Translators and other source information

版权声明
本文为[Program ape DD]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/10/20211002145752189O.html

Scroll to Top