java组合与继承始示例_Java 9功能与示例

java组合与继承始示例

Java 9 is a major release and it has brought us a lot of features for developers. In this article, we will look into Java 9 features in detail.

Java 9是一个主要版本,它为开发人员带来了许多功能。 在本文中,我们将详细研究Java 9功能。

Java 9功能 (Java 9 Features)

java 9 features

Some of the important java 9 features are;


Java 9的一些重要功能是:

  1. Java 9 REPL (JShell)

    Java 9 REPL(JShell)
  2. Factory Methods for Immutable List, Set, Map and Map.Entry

    不可变列表,集合,映射和Map.Entry的工厂方法
  3. Private methods in Interfaces

    接口中的私有方法
  4. Java 9 Module System

    Java 9模块系统
  5. Process API Improvements

    流程API的改进
  6. Try With Resources Improvement

    尝试改善资源
  7. CompletableFuture API Improvements

    CompletableFuture API的改进
  8. Reactive Streams

    React流
  9. Diamond Operator for Anonymous Inner Class

    匿名内部类的钻石运营商
  10. Optional Class Improvements

    可选的班级改进
  11. Stream API Improvements

    流API的改进
  12. Enhanced @Deprecated annotation

    增强的@Deprecated批注
  13. HTTP 2 Client

    HTTP 2客户端
  14. Multi-Resolution Image API

    多分辨率图像API
  15. Miscellaneous Java 9 Features

    Java 9的其他功能

Oracle Corporation is going to release Java SE 9 around the end of March 2017. In this post, I’m going to discuss “Java 9 Features” briefly with some examples.

Oracle Corporation将在2017年3月底左右发布Java SE9。在本文中,我将通过一些示例简要讨论“ Java 9功能”。

  1. Java 9 REPL(JShell) (Java 9 REPL (JShell))

    Oracle Corp has introduced a new tool called “jshell”. It stands for Java Shell and also known as REPL (Read Evaluate Print Loop). It is used to execute and test any Java Constructs like class, interface, enum, object, statements etc. very easily.

    We can download JDK 9 EA (Early Access) software from https://jdk9.java.net/download/

    G:\>jshell
    |  Welcome to JShell -- Version 9-ea
    |  For an introduction type: /help intro
    
    
    jshell> int a = 10
    a ==> 10
    
    jshell> System.out.println("a value = " + a )
    a value = 10

    If you want to know more about REPL tool, Please go through Java 9 REPL Basics (Part-1) and Java 9 REPL Features (Part-2).

    Oracle公司推出了一种名为“ jshell”的新工具。 它代表Java Shell,也称为REPL(读取评估打印循环)。 它用于轻松执行和测试任何Java构造,如类,接口,枚举,对象,语句等。

    我们可以从https://jdk9.java.net/download/下载JDK 9 EA(早期访问)软件。

    如果您想进一步了解REPL工具,请阅读Java 9 REPL基础知识(第1部分)Java 9 REPL功能(第2部分)

  2. 不可变列表,集合,映射和Map.Entry的工厂方法 (Factory Methods for Immutable List, Set, Map and Map.Entry)

    Oracle Corp has introduced some convenient factory methods to create Immutable List, Set, Map and Map.Entry objects. These utility methods are used to create empty or non-empty Collection objects.

    In Java SE 8 and earlier versions, We can use Collections class utility methods like unmodifiableXXX to create Immutable Collection objects. For instance, if we want to create an Immutable List, then we can use Collections.unmodifiableList method.

    However, these Collections.unmodifiableXXX methods are a tedious and verbose approach. To overcome those shortcomings, Oracle Corp has added a couple of utility methods to List, Set and Map interfaces.

    List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set objects as shown below:

    Empty List Example

    List immutableList = List.of();

    Non-Empty List Example

    The Map has two sets of methods: of() methods and ofEntries() methods to create an Immutable Map object and an Immutable Map.Entry object respectively.

    Empty Map Example

    jshell> Map emptyImmutableMap = Map.of()
    emptyImmutableMap ==> {}

    Non-Empty Map Example

    If you want to read more about these utility methods, please go through the following links:

    Oracle Corp引入了一些方便的工厂方法来创建不可变列表,Set,Map和Map.Entry对象。 这些实用程序方法用于创建空或非空的Collection对象。

    在Java SE 8和更早版本中,我们可以使用诸如unmodifiableXXX类的Collections类实用程序方法来创建Immutable Collection对象。 例如,如果要创建一个不可变列表,则可以使用Collections.unmodifiableList方法。

    但是,这些Collections.unmodifiableXXX方法是一种繁琐而冗长的方法。 为了克服这些缺点,Oracle Corp向List,Set和Map接口添加了一些实用程序方法。

    List和Set接口具有“ of()”方法来创建一个空的或不空的不可变List或Set对象,如下所示:

    空列表示例

    List immutableList = List.of();

    非空清单示例

    Map有两组方法: of()方法和ofEntries()方法,分别用于创建Immutable Map对象和Immutable Map.Entry对象。

    空地图示例

    jshell> Map emptyImmutableMap = Map.of()
    emptyImmutableMap ==> {}

    非空地图示例

    如果您想了解有关这些实用程序方法的更多信息,请通过以下链接:

  3. 接口中的私有方法 (Private methods in Interfaces)

    In Java 8, we can provide method implementation in Interfaces using Default and Static methods. However we cannot create private methods in Interfaces.

    To avoid redundant code and more re-usability, Oracle Corp is going to introduce private methods in Java SE 9 Interfaces. From Java SE 9 onwards, we can write private and private static methods too in an interface using a ‘private’ keyword.

    These private methods are like other class private methods only, there is no difference between them.

    public interface Card{
    
      private Long createCardID(){
        // Method implementation goes here.
      }
    
      private static void displayCardDetails(){
        // Method implementation goes here.
      }
    
    }

    If you want to read more about this new feature, please go through this link: Java 9 Private methods in Interface.

    在Java 8中,我们可以使用Default和Static方法在Interfaces中提供方法实现。 但是,我们不能在接口中创建私有方法。

    为了避免冗余代码和提高可重用性,Oracle Corp.将在Java SE 9接口中引入私有方法。 从Java SE 9开始,我们也可以使用'private'关键字在接口中编写私有和私有静态方法。

    这些私有方法仅类似于其他类的私有方法,它们之间没有区别。

    如果您想了解更多有关此新功能的信息,请访问以下链接: Interface中的Java 9 Private方法

  4. Java 9模块系统 (Java 9 Module System)

    One of the big changes or java 9 feature is the Module System. Oracle Corp is going to introduce the following features as part of Jigsaw Project.

    • Modular JDK
    • Modular Java Source Code
    • Modular Run-time Images
    • Encapsulate Java Internal APIs
    • Java Platform Module System

    Before Java SE 9 versions, we are using Monolithic Jars to develop Java-Based applications. This architecture has a lot of limitations and drawbacks. To avoid all these shortcomings, Java SE 9 is coming with the Module System.

    JDK 9 is coming with 92 modules (may change in final release). We can use JDK Modules and also we can create our own modules as shown below:

    Simple Module Example

    module com.foo.bar { }

    Here we are using ‘module’ to create a simple module. Each module has a name, related code, and other resources.

    To read more details about this new architecture and hands-on experience, please go through my original tutorials here:

    模块系统是Java 9的一大变化。 Oracle公司将在Jigsaw Project中引入以下功能。

    • 模块化JDK
    • 模块化Java源代码
    • 模块化运行时映像
    • 封装Java内部API
    • Java平台模块系统

    在Java SE 9版本之前,我们使用Monolithic Jars开发基于Java的应用程序。 这种体系结构有很多局限性和缺点。 为避免所有这些缺点,Java SE 9随模块系统一起提供。

    JDK 9随附92个模块(最终版本可能会更改)。 我们可以使用JDK模块,也可以创建自己的模块,如下所示:

    简单模块示例

    在这里,我们使用“模块”来创建一个简单的模块。 每个模块都有一个名称,相关代码和其他资源。

    要阅读有关此新架构和动手体验的更多详细信息,请在此处浏览我的原始教程:

  5. 流程API的改进 (Process API Improvements)

    Java SE 9 is coming with some improvements in Process API. They have added couple new classes and methods to ease the controlling and managing of OS processes.

    Two new interfcase in Process API:

    • java.lang.ProcessHandle
    • java.lang.ProcessHandle.Info

    Process API example

    ProcessHandle currentProcess = ProcessHandle.current();
     System.out.println("Current Process Id: = " + currentProcess.getPid());

    Java SE 9在Process API中进行了一些改进。 他们添加了一些新的类和方法来简化OS进程的控制和管理。

    Process API中的两个新的interfcase:

    • java.lang.ProcessHandle
    • java.lang.ProcessHandle.Info

    流程API示例

  6. 尝试改善资源 (Try With Resources Improvement)

    We know, Java SE 7 has introduced a new exception handling construct: Try-With-Resources to manage resources automatically. The main goal of this new statement is “Automatic Better Resource Management”.

    Java SE 9 is going to provide some improvements to this statement to avoid some more verbosity and improve some Readability.

    Java SE 7 example

    void testARM_Before_Java9() throws IOException{
     BufferedReader reader1 = new BufferedReader(new FileReader("journaldev.txt"));
     try (BufferedReader reader2 = reader1) {
       System.out.println(reader2.readLine());
     }
    }

    Java 9 example

    To read more about this new feature, please go through my original tutorial at: Java 9 Try-With-Resources Improvements

    我们知道,Java SE 7引入了一种新的异常处理结构:Try-With-Resources以自动管理资源。 这一新声明的主要目标是“自动更好的资源管理”。

    Java SE 9将对该语句进行一些改进,以避免更多的冗长和提高一些可读性。

    Java SE 7示例

    void testARM_Before_Java9() throws IOException{
     BufferedReader reader1 = new BufferedReader(new FileReader("journaldev.txt"));
     try (BufferedReader reader2 = reader1) {
       System.out.println(reader2.readLine());
     }
    }

    Java 9示例

    要了解有关此新功能的更多信息,请浏览我的原始教程,网址为: Java 9 Try-With-Resources Improvements

  7. CompletableFuture API的改进 (CompletableFuture API Improvements)

    In Java SE 9, Oracle Corp is going to improve CompletableFuture API to solve some problems raised in Java SE 8. They are going add to support some delays and timeouts, some utility methods and better sub-classing.

    Executor exe = CompletableFuture.delayedExecutor(50L, TimeUnit.SECONDS);

    Here delayedExecutor() is a static utility method used to return a new Executor that submits a task to the default executor after the given delay.

    在Java SE 9中,Oracle Corp将改进CompletableFuture API,以解决Java SE 8中提出的一些问题。它们将被添加以支持某些延迟和超时,某些实用程序方法以及更好的子类化。

    这里的delayExecutor()是一种静态实用程序方法,用于返回新的Executor,该Executor在给定的延迟后将任务提交给默认的执行程序。

  8. React流 (Reactive Streams)

    Nowadays, Reactive Programming has become very popular in developing applications to get some beautiful benefits. Scala, Play, Akka, etc. Frameworks have already integrated Reactive Streams and getting many benefits. Oracle Corps is also introducing new Reactive Streams API in Java SE 9.

    Java SE 9 Reactive Streams API is a Publish/Subscribe Framework to implement Asynchronous, Scalable and Parallel applications very easily using Java language.

    Java SE 9 has introduced the following API to develop Reactive Streams in Java-based applications.

    • java.util.concurrent.Flow
    • java.util.concurrent.Flow.Publisher
    • java.util.concurrent.Flow.Subscriber
    • java.util.concurrent.Flow.Processor

    Read more at Java 9 Reactive Streams.

    如今,响应式编程已在开发应用程序中变得非常流行,以获得一些美丽的好处。 Scala,Play,Akka等。框架已经集成了Reactive Streams,并获得了很多好处。 Oracle Corps还在Java SE 9中引入了新的Reactive Streams API。

    Java SE 9 Reactive Streams API是一个发布/订阅框架,用于使用Java语言非常轻松地实现异步,可伸缩和并行应用程序。

    Java SE 9引入了以下API,以在基于Java的应用程序中开发响应流。

    • java.util.concurrent.Flow
    • java.util.concurrent.Flow.Publisher
    • java.util.concurrent.Flow.Subscriber
    • java.util.concurrent.Flow.Processor

    Java 9 Reactive Streams中阅读更多内容。

  9. 匿名内部类的钻石运营商 (Diamond Operator for Anonymous Inner Class)

    We know, Java SE 7 has introduced one new feature: Diamond Operator to avoid redundant code and verbosity, to improve readability. However, in Java SE 8, Oracle Corp (Java Library Developer) has found that some limitations in the use of Diamond operator with Anonymous Inner Class. They have fixed those issues and going to release them as part of Java 9.

    public List getEmployee(String empid){
         // Code to get Employee details from Data Store
         return new List(emp){ };
      }

    Here we are using just “List” without specifying the type parameter.

    我们知道,Java SE 7引入了一项新功能:Diamond运算符可避免冗余代码和冗长,提高可读性。 但是,在Java SE 8中,Oracle Corp(Java库开发人员)发现在将Diamond运算符与匿名内部类一起使用时存在一些限制。 他们已解决了这些问题,并将其作为Java 9的一部分发布。

    在这里,我们仅使用“列表”而不指定类型参数。

  10. 可选的班级改进 (Optional Class Improvements)

    In Java SE 9, Oracle Corp has added some useful new methods to java.util.Optional class. Here I’m going to discuss about one of those methods with some simple example: stream method

    If a value present in the given Optional object, this stream() method returns a sequential Stream with that value. Otherwise, it returns an empty Stream.

    They have added “stream()” method to work on Optional objects lazily as shown below:

    Stream<Optional> emp = getEmployee(id)
    Stream empStream = emp.flatMap(Optional::stream)

    Here Optional.stream() method is used to convert a Stream of Optional of Employee object into a Stream of Employee so that we can work on this result lazily in the result code.

    To understand more about this feature with more examples and to read more new methods added to Optional class, please go through my original tutorial at: Java SE 9: Optional Class Improvements

    在Java SE 9中,Oracle Corp向java.util.Optional类添加了一些有用的新方法。 在这里,我将通过一些简单的示例来讨论其中一种方法:流方法

    如果给定的Optional对象中存在一个值,则此stream()方法将返回一个具有该值的顺序Stream。 否则,它将返回一个空Stream。

    他们添加了“ stream()”方法来延迟对可选对象的工作,如下所示:

    这里的Optional.stream()方法用于将Employee的Optional的Stream对象转换为Employee的Stream,以便我们可以在结果代码中懒惰地处理此结果。

    要了解更多有关此功能的更多示例,并阅读更多添加到Optional类的新方法,请浏览我的原始教程,网址为: Java SE 9:Optional Class Improvements

  11. 流API的改进 (Stream API Improvements)

    In Java SE 9, Oracle Corp has added four useful new methods to java.util.Stream interface. As Stream is an interface, all those new implemented methods are default methods. Two of them are very important: dropWhile and takeWhile methods

    If you are familiar with Scala Language or any Functions programming language, you will definitely know about these methods. These are very useful methods in writing some functional style code. Let us discuss the takeWhile utility method here.

    This takeWhile() takes a predicate as an argument and returns a Stream of the subset of the given Stream values until that Predicate returns false for the first time. If the first value does NOT satisfy that Predicate, it just returns an empty Stream.

    jshell> Stream.of(1,2,3,4,5,6,7,8,9,10).takeWhile(i -> i < 5 )
                     .forEach(System.out::println);
    1
    2
    3
    4

    To read more about takeWhile and dropWhile methods and other new methods, please go through my original tutorial at: Java SE 9: Stream API Improvements

    在Java SE 9中,Oracle Corp向java.util.Stream接口添加了四个有用的新方法。 因为Stream是接口,所以所有这些新实现的方法都是默认方法。 其中两个非常重要:dropWhile和takeWhile方法

    如果您熟悉Scala语言或任何函数编程语言,则一定会知道这些方法。 这些是编写某些功能样式代码的非常有用的方法。 让我们在这里讨论takeWhile实用程序方法。

    该takeWhile()将谓词作为参数,并返回给定Stream值的子集的Stream,直到该谓词第一次返回false为止。 如果第一个值不满足该谓词,则仅返回一个空Stream。

    要阅读有关takeWhile和dropWhile方法以及其他新方法的更多信息,请阅读以下原始教程: Java SE 9:Stream API的改进

  12. 增强的@Deprecated批注 (Enhanced @Deprecated annotation)

    In Java SE 8 and earlier versions, @Deprecated annotation is just a Marker interface without any methods. It is used to mark a Java API that is a class, field, method, interface, constructor, enum etc.

    In Java SE 9, Oracle Corp has enhanced @Deprecated annotation to provide more information about deprecated API and also provide a Tool to analyze an application’s static usage of deprecated APIs. They have add two methods to this Deprecated interface: forRemoval and since to serve this information.

    在Java SE 8和更早版本中,@ Deprecated注释只是一个Marker接口,没有任何方法。 它用于标记Java API,它是类,字段,方法,接口,构造函数,枚举等。

    在Java SE 9中,Oracle Corp增强了@Deprecated批注,以提供有关不赞成使用的API的更多信息,并且还提供了一种工具来分析应用程序对不赞成使用的API的静态使用情况。 他们在此不推荐使用的接口中添加了两种方法: forRemoval从那时起提供此信息。

  13. HTTP 2客户端 (HTTP 2 Client)

    In Java SE 9, Oracle Corp is going to release New HTTP 2 Client API to support HTTP/2 protocol and WebSocket features. As existing or Legacy HTTP Client API has numerous issues (like supports HTTP/1.1 protocol and does not support HTTP/2 protocol and WebSocket, works only in Blocking mode and lot of performance issues.), they are replacing this HttpURLConnection API with new HTTP client.

    They are going to introduce a new HTTP 2 Client API under the “java.net.http” package. It supports both HTTP/1.1 and HTTP/2 protocols. It supports both Synchronous (Blocking Mode) and Asynchronous Modes. It supports Asynchronous Mode using the WebSocket API.

    We can see this new API at https://download.java.net/java/jdk9/docs/api/java/net/http/package-summary.html

    HTTP 2 Client Example

    jshell> import java.net.http.*
    
    jshell> import static java.net.http.HttpRequest.*
    
    jshell> import static java.net.http.HttpResponse.*
    
    jshell> URI uri = new URI("https://rams4java.blogspot.co.uk/2016/05/java-news.html")
    uri ==> https://rams4java.blogspot.co.uk/2016/05/java-news.html
    
    jshell> HttpResponse response = HttpRequest.create(uri).body(noBody()).GET().response()
    response ==> java.net.http.HttpResponseImpl@79efed2d
    
    jshell> System.out.println("Response was " + response.body(asString()))

    Please go through my original tutorial at: Java SE 9: HTTP 2 Client to understand HTTP/2 protocol & WebSocket, Benefits of new API and Drawbacks of OLD API with some useful examples.

    在Java SE 9中,Oracle Corp.将发布新的HTTP 2 Client API,以支持HTTP / 2协议和WebSocket功能。 由于现有的或旧版HTTP客户端API存在许多问题(例如,支持HTTP / 1.1协议并且不支持HTTP / 2协议和WebSocket,仅在阻止模式下工作,并且存在很多性能问题。),他们将HttpURLConnection API替换为新HTTP客户。

    他们将在“ java.net.http”包下引入一个新的HTTP 2 Client API。 它同时支持HTTP / 1.1和HTTP / 2协议。 它同时支持同步(阻止模式)和异步模式。 它使用WebSocket API支持异步模式。

    我们可以在https://download.java.net/java/jdk9/docs/api/java/net/http/package-summary.html上看到此新API。

    HTTP 2客户端示例

    请浏览我的原始教程,网址为: Java SE 9:HTTP 2 Client,以了解HTTP / 2协议和WebSocket,新API的好处以及OLD API的缺点以及一些有用的示例。

  14. 多分辨率图像API (Multi-Resolution Image API)

    In Java SE 9, Oracle Corp is going to introduce a new Multi-Resolution Image API. Important interface in this API is MultiResolutionImage . It is available in java.awt.image package.

    MultiResolutionImage encapsulates a set of images with different Height and Widths (that is different resolutions) and allows us to query them with our requirements.

    在Java SE 9中,Oracle Corp将引入一个新的Multi-Resolution Image API。 此API中的重要接口是MultiResolutionImage。 在java.awt.image包中可用。

    MultiResolutionImage封装了一组具有不同高度和宽度(即不同分辨率)的图像,并允许我们根据需求查询它们。

  15. Java 9的其他功能 (Miscellaneous Java 9 Features)

    In this section, I will just list out some miscellaneous Java SE 9 New Features. I’m NOT saying these are less important features. They are also important and useful to understand them very well with some useful examples.

    As of now, I did not get enough information about these features. That’s why I am going to list them here for a brief understanding. I will pick up these features one by one and add to the above section with a brief discussion and example. And finally write a separate tutorial later.

    • GC (Garbage Collector) Improvements
    • Stack-Walking API
    • Filter Incoming Serialization Data
    • Deprecate the Applet API
    • Indify String Concatenation
    • Enhanced Method Handles
    • Java Platform Logging API and Service
    • Compact Strings
    • Parser API for Nashorn
    • Javadoc Search
    • HTML5 Javadoc

    在本部分中,我将列出一些Java SE 9的其他新功能。 我并不是说这些不是那么重要的功能。 通过一些有用的示例,它们对于理解它们也非常重要和有用。

    到目前为止,我还没有获得有关这些功能的足够信息。 这就是为什么我将在此处列出它们以进行简要了解。 我将逐一介绍这些功能,并通过简短的讨论和示例将其添加到以上部分中。 最后,以后再写一个单独的教程。

    • GC(垃圾收集器)改进
    • 堆栈步行API
    • 筛选传入的序列化数据
    • 弃用Applet API
    • 字符串化连接
    • 增强的方法句柄
    • Java平台日志记录API和服务
    • 紧凑弦
    • Nashorn的解析器API
    • Javadoc搜索
    • HTML5 Javadoc

I will pickup these java 9 features one by one and update them with enough description and examples.

我将逐一介绍这些Java 9功能,并用足够的描述和示例更新它们。

That’s all about Java 9 features in brief with examples.

这就是有关Java 9功能的简短示例。

翻译自: https://www.journaldev.com/13121/java-9-features-with-examples

java组合与继承始示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值