Java11 is a LTS version after Java8. Java8 of LTS will expire this year, after Java8, Java11 is the best choice. New features Java9 to Java11 although not span Java8, but in the virtual machine level has been greatly upgraded. By Benjamin of this blog, we look Java11 any different.
Java11 utilization rate is not high, there are still a lot of people use Java8 in a production environment. This article will use examples to explain Java9 into Java11 most important new features. This article uses the code to explain the new features, there will be a large section of text.
Local variable type inference
Java 10 There is a new keyword var
, when a local variable declaration var
does not need to specify the particular data type (local variable refers to the method of variables declared in).
In 10 previous versions of Java, you need to declare variables:
String text = "Hello Java 9";
复制代码
In Java 10, you can use var
an alternative String
. The compiler to infer the type of a variable based on variable assignment. In the following example text
the type is String
:
var text = "Hello Java 10";
复制代码
By var
variable declaration remains static type. Another type can not be assigned to the variables already. The following piece of code will not compile by:
var text = "Hello Java 11";
text = 23;
复制代码
Can final
be prevented declared var
variables are repeated assignment:
final var text = "Banana";
text = "Joe"; // 编译报错
复制代码
var
Variables must be assigned a value type of clear, for no assignment or the compiler can not infer the type of a variable, it will compile error. The following code will not compile:
var a;
var nothing = null;
var lambda = () -> System.out.println("Pity!");
var method = this::someMethod;
复制代码
Local type inference when dealing with very generic code. In the following example, current
the type Map<String, List<Integer>>
, if used var
instead Map<String, List<Integer>>
, can be much less sample code:
var myList = new ArrayList<Map<String, List<Integer>>>();
for (var current : myList) {
System.out.println(current);
}
复制代码
In the Java 11 var
it can also be used for parameter lambda, but need to add @Nullable
annotations:
Predicate<String> predicate = (@Nullable var a ) -> true;
复制代码
Tip: In Intellij IDEA in, you can select a variable, press
CMD/CTRL
to show the true type of a variable (keyboard can be used for partyCTRL + J
).
HTTP Client
Java 9
Hidden in a new processing API Http request HttpClient
. To Java11
this API has been perfect, and in the JDK java.net
under the package. Take a look at the API can do something about it.
This new HttpClient
can be synchronous or asynchronous use. Synchronous request will block the current thread until the response is returned. BodyHandlers
It defines the expected return data type. (eg string, file or byte array):
var request = HttpRequest.newBuilder()
.uri(URI.create("https://winterbe.com"))
.GET()
.build();
var client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
复制代码
The same request can be processed asynchronously. Call sendAsync
does not block the current thread and a return CompleteFuture
to build a pipeline asynchronous operation.
var request = HttpRequest.newBuilder()
.uri(URI.create("https://winterbe.com"))
.build();
var client = HttpClient.newHttpClient();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
复制代码
It may be omitted
.GET()
, the default is the request method.
By the following example POST
to a method of URL
transmitting data. BodyHandlers
Type can also be used to define the data needs to send a request, such as strings , byte array , a file or input stream :
var request = HttpRequest.newBuilder()
.uri(URI.create("https://postman-echo.com/post"))
.header("Content-Type", "text/plain")
.POST(HttpRequest.BodyPublishers.ofString("Hi there!"))
.build();
var client = HttpClient.newHttpClient();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode()); // 200
复制代码
The last example demonstrates how BASIC-AUTH
to authenticate:
var request = HttpRequest.newBuilder()
.uri(URI.create("https://postman-echo.com/basic-auth"))
.build();
var client = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("postman", "password".toCharArray());
}
})
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode()); // 200
复制代码
Collections
Java in containers such as List
, Set
, Map
has expanded a lot of new ways. List.of
Will create a new parameter based on immutable list
, List.copy
it created this list
immutable copy.
var list = List.of("A", "B", "C");
var copy = List.copyOf(List);
System.out.println(list == copy); // true
复制代码
Because list
already are immutable, no need to create another instance when copying, so lisi
and copy
points to the same instance. However, if you want to copy a variable object, you'll create a new instance to ensure that changes to the original object does not affect the copied object.
var list = new ArrayList<String>();
var copy = List.copyOf(list);
System.out.println(list == copy);
复制代码
When creating immutable map when objects do not need to manually create a map, only need to use Map.of
the method and alternate key value can be passed.
var map = Map.of("A", 1, "B", 2);
System.out.println(map);
复制代码
No change in the API Java 11 immutable container. However, if you attempt to add an immutable container or reduction elements, it will throw
java.lang.UnsupportedOperationException
an exception. Fortunately,Intellij IDEA
it will issue a warning when you try to modify an immutable container.
Streams
Streams
In Java8 added new features added in the back and three new methods. Stream.ofNullable
The method to construct the flow through a single element:
Stream.ofNullable(null)
.count(); // 0
复制代码
dropWhile
And the takeWhile
method can accept a predicate
parameter to decide whether to comply with the conditions of the elements cleared out from the stream.
It is a predicate function programming interface
Optionals
Optionals
Also receives some pretty useful methods. Optinals example, can now be transformed into simple stream or returned to another optional standby an empty optional.
Optional.of("foo").orElseThrow(); // foo
Optional.of("foo").stream().count(); // 1
Optional.ofNullable(null)
.or(() -> Optional.of("fallback"))
.get(); // fallback
复制代码
Strings
String
The base class also added a number of check blanks and a method for calculating the number of lines of the string.
" ".isBlank(); // true
" Foo Bar ".strip(); // "Foo Bar"
" Foo Bar ".stripTrailing(); // " Foo Bar"
" Foo Bar ".stripLeading(); // "Foo Bar "
"Java".repeat(3); // "JavaJavaJava"
"A\nB\nC".lines().count(); // 3
复制代码
InputStreams
Finally, a brief talk about InputStream
provides a very helpful way to transfer data to OutputStream
, the following example in the original data transmission time can often see.
var classLoader = ClassLoader.getSystemClassLoader();
var inputStream = classLoader.getResourceAsStream("myFile.txt");
var tempFile = File.createTempFile("myFileCopy", "txt");
try (var outputStream = new FileOutputStream(tempFile)) {
inputStream.transferTo(outputStream);
}
复制代码
Other characteristics of the JVM
Above these things I think Java8 to Java11 the most interesting new features. But the new features far more than that. The following features in the latest versions of Java are:
- Flow API for reactive programming
- Java Module System
- Application Class Data Sharing
- Dynamic Class-File Constants
- Java REPL (JShell)
- Flight Recorder
- Unicode 10
- G1: Full Parallel Garbage Collector
- ZGC: Scalable Low-Latency Garbage Collector
- Epsilon: No-Op Garbage Collector
- Deprecate the Nashorn JavaScript Engine
- ...
The next step
Many people (including me) still use Java8 in a production environment. However, by the year 2020, Java8 of TLS over. So now it is a good opportunity to migrate to the Java11. I wrote a migration guide to help you migrate from Java8 to Java11. At the same time you should also read my Java8 and Stream API tutorial to learn how to use a more fashionable way of development. These have been published to the source on GitHub, and casually play (if you like, tap the star).
(Finish)
No micro-channel public attention, something else to talk