Home  >  Article  >  Java  >  Detailed explanation of nine new features of Java

Detailed explanation of nine new features of Java

Y2J
Y2JOriginal
2017-05-15 09:30:301378browse

More than three years after Java 8 was released, the July 2017 release date for the next version is approaching. You may have heard about Java 9's module system, but there are many other updates in this new version. Here are nine exciting new features coming with Java 9. Friends who need it can refer to it for reference. Let’s take a look below.

This article mainly shares with you nine new features in Java 9, which has certain reference and learning value for everyone. Let’s take a look at the detailed introduction:

1. Java platform-level module system

The defining function of Java 9 is a brand-new module system. As code bases get larger, the chances of creating complex, convoluted "spaghetti code" increase exponentially. At this time, you have to face two basic problems: it is difficult to truly encapsulate the code, and the system does not have a clear concept of the dependencies between different parts (that is, JAR files). Every public class can be accessed by any other public class under the class path, which can lead to inadvertent use of API that is not intended to be publicly accessible. In addition, there are problems with the classpath itself: how do you know that all the required JARs are already there, or if there are duplicate entries? The module system solves both problems.

Modular JAR files contain an additional module descriptor. In this module descriptor, dependencies on other modules are expressed through "requires". In addition, the "exports" statement controls which packages can be accessed by other modules. All packages that are not exported are encapsulated in modules by default. The following is an example of a module descriptor, present in the "module-info.java" file:


module blog {
 exports com.pluralsight.blog;

 requires cms;
}

We can display the module as follows:

Please note: Both modules contain encapsulated packages as they are not exported (visualized using an orange shield). No one uses classes from these packages by accident. The Java platform itself is also modularized using its own module system. By encapsulating JDK's internal classes, the platform is more secure and continuous improvement is easier.

2. LinkingWhen you use modules with explicit dependencies and a modular JDK, new possibilities appear. . Your application module will now declare its dependencies on other application modules and on the JDK modules it uses. Why not use this information to create a minimal runtime environment that contains only those modules needed to run the application? This is possible with the new jlink tool in Java 9. You can create a minimal runtime image that is optimized for your application without using a fully loaded JDK

installation

version.

3. JShell: Interactive Java REPLXu

multi-language

already has interactiveprogrammingEnvironment, Java has now joined the club. You can launch jshell from the console and initiate input and execution of Java code directly. jshell's instant feedback makes it a great tool for exploring APIs and trying out language features.

Testing a Java

Regular Expressions

is a great example of how jshell can make your life easier. Interactive shells can also provide a great teaching environment and increase productivity, you can learn more here. In the process of teaching people how to write Java, there is no need to explain the "public static void main(String [] args)" nonsense anymore.

4. Improved JavadocSometimes little things can make a big difference. Are you like me and have been using Google to find the correct Javadoc page? This is no longer needed. Javadoc now supports

search

within the API documentation. Additionally, Javadoc output is now compliant with HTML5 standards. Additionally, you'll notice that every Javadoc page contains information about the source of a JDK module class or interface.


五、集合工厂方法

通常,您希望在代码中创建一个集合(例如,ListSet ),并直接用一些元素填充它。 实例化集合,几个 “add” 调用,使得代码重复。 Java 9,添加了几种集合工厂方法:


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

除了更短和更好阅读之外,这些方法也可以避免您选择特定的集合实现。 事实上,从工厂方法返回已放入数个元素的集合实现是高度优化的。这是可能的,因为它们是不可变的:在创建后,继续添加元素到这些集合会导致 “UnsupportedOperationException” 。

六、改进的 Stream API

长期以来,Stream API 都是 Java 标准库最好的改进之一。通过这套 API 可以在集合上建立用于转换的申明管道。在 Java 9 中它会变得更好。Stream 接口中添加了 4 个新的方法:dropWhile, takeWhile, ofNullable。还有个 iterate 方法的新重载方法,可以让你提供一个 Predicate (判断条件)来指定什么时候结束迭代:


IntStream.iterate(1, i -> i < 100, i -> i + 1).forEach(System.out::println);

第二个参数是一个 Lambda,它会在当前 IntStream 中的元素到达 100 的时候返回 true。因此这个简单的示例是向控制台打印 1 到 99。

除了对 Stream 本身的扩展,Optional 和 Stream 之间的结合也得到了改进。现在可以通过 Optional 的新方法 `stram` 将一个 Optional 对象转换为一个(可能是空的) Stream 对象:


Stream<Integer> s = Optional.of(1).stream();

在组合复杂的 Stream 管道时,将 Optional 转换为 Stream 非常有用。

七、私有接口方法

Java 8 为我们带来了接口的默认方法。 接口现在也可以包含行为,而不仅仅是方法签名。 但是,如果在接口上有几个默认方法,代码几乎相同,会发生什么情况? 通常,您将重构这些方法,调用一个可复用的私有方法。 但默认方法不能是私有的。 将复用代码创建为一个默认方法不是一个解决方案,因为该辅助方法会成为公共API的一部分。 使用 Java 9,您可以向接口添加私有辅助方法来解决此问题:


public interface MyInterface {

  void normalInterfaceMethod();

  default void interfaceMethodWithDefault() { init(); }

  default void anotherDefaultMethod() { init(); }

  // This method is not part of the public API exposed by MyInterface
  private void init() { System.out.println("Initializing"); }
}

如果您使用默认方法开发 API ,那么私有接口方法可能有助于构建其实现。

八、HTTP/2

Java 9 中有新的方式来处理 HTTP 调用。这个迟到的特性用于代替老旧的 `HttpURLConnection` API,并提供对 WebSocket 和 HTTP/2 的支持。注意:新的 HttpClient API 在 Java 9 中以所谓的孵化器模块交付。也就是说,这套 API 不能保证 100% 完成。不过你可以在 Java 9 中开始使用这套 API:


HttpClient client = HttpClient.newHttpClient();

HttpRequest req =
  HttpRequest.newBuilder(URI.create("http://www.google.com"))
       .header("User-Agent","Java")
       .GET()
       .build();


HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandler.asString());

除了这个简单的请求/响应模型之外,HttpClient 还提供了新的 API 来处理 HTTP/2 的特性,比如流和服务端推送。

九、 多版本兼容 JAR

我们最后要来着重介绍的这个特性对于库的维护者而言是个特别好的消息。当一个新版本的 Java 出现的时候,你的库用户要花费数年时间才会切换到这个新的版本。这就意味着库得去向后兼容你想要支持的最老的 Java 版本 (许多情况下就是 Java 6 或者 7)。这实际上意味着未来的很长一段时间,你都不能在库中运用 Java 9 所提供的新特性。幸运的是,多版本兼容 JAR 功能能让你创建仅在特定版本的 Java 环境中运行库程序时选择使用的 class 版本:


multirelease.jar
├── META-INF
│  └── versions
│    └── 9
│      └── multirelease
│        └── Helper.class
├── multirelease
  ├── Helper.class
  └── Main.class

在上述场景中, multirelease.jar 可以在 Java 9 中使用, 不过 Helper 这个类使用的不是顶层的 multirelease.Helper 这个 class, 而是处在“META-INF/versions/9”下面的这个。这是特别为 Java 9 准备的 class 版本,可以运用 Java 9 所提供的特性和库。同时,在早期的 Java 诸版本中使用这个 JAR 也是能运行的,因为较老版本的 Java 只会看到顶层的这个 Helper 类。

如你所见,Java 9 提供了一大堆或大或小的功能特性,你准备好了么?

Summary

[Related Recommendations]

1. Special Recommendations: "php programmer Toolbox" V0.1 version download

2. Java free video tutorial

3. Comprehensive analysis of Java annotations

The above is the detailed content of Detailed explanation of nine new features of Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn