New Features in Java 8 – Java 8的新功能

最后修改: 2016年 5月 31日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll have a quick look at some of the most interesting new features in Java 8.

在本教程中,我们将快速浏览一下Java 8中一些最有趣的新功能。

We’ll talk about interface default and static methods, method reference and Optional.

我们将谈论接口默认和静态方法、方法引用和Optional。

We have already covered some the features of the Java 8 release — stream API, lambda expressions and functional interfaces — as they’re comprehensive topics that deserve a separate look.

我们已经介绍了Java 8版本的一些特性–stream APIlambda表达式和功能接口–因为它们是全面的主题,值得单独看一下。

2. Interface Default and Static Methods

2.接口默认方法和静态方法

Before Java 8, interfaces could have only public abstract methods. It was not possible to add new functionality to the existing interface without forcing all implementing classes to create an implementation of the new methods, nor was it possible to create interface methods with an implementation.

在Java 8之前,接口只能有公共抽象方法。如果不强迫所有的实现类创建新方法的实现,就不可能为现有的接口添加新功能,也不可能创建带有实现的接口方法。

Starting with Java 8, interfaces can have static and default methods that, despite being declared in an interface, have a defined behavior.

从Java 8开始,接口可以有staticdefault方法,这些方法尽管是在接口中声明的,但有一个定义的行为。

2.1. Static Method

2.1.静态方法

Consider this method of the interface (let’s call this interface Vehicle):

考虑一下接口的这个方法(我们把这个接口叫做Vehicle)。

static String producer() {
    return "N&F Vehicles";
}

The static producer() method is available only through and inside of an interface. It can’t be overridden by an implementing class.

静态的producer()方法只能通过接口并在其内部使用。它不能被一个实现类重载。

To call it outside the interface, the standard approach for static method call should be used:

要在接口之外调用它,应该使用静态方法调用的标准方法。

String producer = Vehicle.producer();

2.2. Default Method

2.2.默认方法

Default methods are declared using the new default keyword. These are accessible through the instance of the implementing class and can be overridden.

默认方法是使用新的default关键字来声明的。这些方法可以通过实现类的实例来访问,并且可以被重写。

Let’s add a default method to our Vehicle interface, which will also make a call to the static method of this interface:

让我们为我们的Vehicle接口添加一个default方法,它也将对这个接口的static方法进行调用。

default String getOverview() {
    return "ATV made by " + producer();
}

Assume that this interface is implemented by the class VehicleImpl.

假设这个接口是由VehicleImpl类实现的。

For executing the default method, an instance of this class should be created:

为了执行default方法,应该创建该类的一个实例。

Vehicle vehicle = new VehicleImpl();
String overview = vehicle.getOverview();

3. Method References

3.方法参考

Method reference can be used as a shorter and more readable alternative for a lambda expression that only calls an existing method. There are four variants of method references.

方法引用可以作为一种更短、更易读的方法,替代只调用一个现有方法的lambda表达式。有四种方法引用的变体。

3.1. Reference to a Static Method

3.1.对一个静态方法的引用

The reference to a static method holds the syntax ContainingClass::methodName.

对静态方法的引用持有ContainingClass::methodName.语法。

We’ll try to count all empty strings in the List<String> with the help of Stream API:

我们将尝试在Stream API的帮助下计算List<String>中的所有空字符串。

boolean isReal = list.stream().anyMatch(u -> User.isRealUser(u));

Let’s take a closer look at lambda expression in the anyMatch() method. It just makes a call to a static method isRealUser(User user) of the User class.

让我们仔细看看anyMatch()方法中的lambda表达式。它只是对User类的静态方法isRealUser(User user)进行了调用。

So, it can be substituted with a reference to a static method:

所以,它可以用一个静态方法的引用来代替。

boolean isReal = list.stream().anyMatch(User::isRealUser);

This type of code looks much more informative.

这种类型的代码看起来信息量更大。

3.2. Reference to an Instance Method

3.2.对实例方法的引用

The reference to an instance method holds the syntax containingInstance::methodName.

对一个实例方法的引用持有语法 containingInstance::methodName

The following code calls method isLegalName(String string) of type User, which validates an input parameter:

下面的代码调用了isLegalName(String string)类型User的方法,它验证了一个输入参数。

User user = new User();
boolean isLegalName = list.stream().anyMatch(user::isLegalName);

3.3. Reference to an Instance Method of an Object of a Particular Type

3.3.对某一特定类型的对象的实例方法的引用

This reference method takes the syntax ContainingType::methodName.

这个参考方法的语法为 ContainingType::methodName

Let’s look at an example:

我们来看看一个例子。

long count = list.stream().filter(String::isEmpty).count();

3.4. Reference to a Constructor

3.4.对构造函数的引用

A reference to a constructor takes the syntax ClassName::new.

对构造函数的引用采用的语法是 ClassName::new.

As constructor in Java is a special method, method reference could be applied to it too, with the help of new as a method name:

由于Java中的构造函数是一个特殊的方法,方法引用也可以应用于它,借助于new作为方法名。

Stream<User> stream = list.stream().map(User::new);

4. Optional<T>

4.可选<T>

Before Java 8, developers had to carefully validate values they referred to because of the possibility of throwing the NullPointerException (NPE). All these checks demanded a pretty annoying and error-prone boilerplate code.

在Java 8之前,开发人员必须仔细验证他们所引用的值,因为有可能抛出NullPointerException(NPE)。所有这些检查都需要一个相当烦人的、容易出错的模板代码。

Java 8 Optional<T> class can help to handle situations where there is a possibility of getting the NPE. It works as a container for the object of type T. It can return a value of this object if this value is not a null. When the value inside this container is null, it allows doing some predefined actions instead of throwing NPE.

Java 8 Optional<T>类可以帮助处理有可能得到NPE的情况。它作为T类型对象的一个容器。如果这个值不是null,它可以返回这个对象的一个值。当这个容器中的值是null时,它允许做一些预定义的动作而不是抛出NPE

4.1. Creation of the Optional<T>

4.1.创建可选<T>

An instance of the Optional class can be created with the help of its static methods.

Optional类的一个实例可以在其静态方法的帮助下被创建。

Let’s look at how to return an empty Optional:

我们来看看如何返回一个空的Optional

Optional<String> optional = Optional.empty();

Next, we return an Optional that contains a non-null value:

接下来,我们返回一个Optional,其中包含一个非空值。

String str = "value";
Optional<String> optional = Optional.of(str);

Finally, here’s how to return an Optional with a specific value or an empty Optional if the parameter is null:

最后,这里是如何返回一个带有特定值的Optional,或者在参数为null时返回一个空的Optional

Optional<String> optional = Optional.ofNullable(getString());

4.2. Optional<T> Usage

4.2. 可选<T> 使用方法

Let’s say we expect to get a List<String>, and in the case of null, we want to substitute it with a new instance of an ArrayList<String>.

假设我们期望得到一个List<String>,在null的情况下,我们想用一个新的ArrayList<String>实例来替代它。

With pre-Java 8’s code, we need to do something like this:

对于Java 8之前的代码,我们需要做这样的事情。

List<String> list = getList();
List<String> listOpt = list != null ? list : new ArrayList<>();

With Java 8, the same functionality can be achieved with a much shorter code:

使用Java 8,同样的功能可以用更短的代码实现。

List<String> listOpt = getList().orElseGet(() -> new ArrayList<>());

There is even more boilerplate code when we need to reach some object’s field in the old way.

当我们需要用老方法到达某个对象的字段时,甚至有更多的模板代码。

Assume we have an object of type User that has a field of type Address with a field street of type String, and we need to return a value of the street field if some exist or a default value if street is null:

假设我们有一个User类型的对象,它有一个Address类型的字段street类型的String,我们需要返回street字段的一个值,如果存在一些,或者如果streetnull,则需要一个默认值。

User user = getUser();
if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        String street = address.getStreet();
        if (street != null) {
            return street;
        }
    }
}
return "not specified";

This can be simplified with Optional:

这可以用Optional来简化。

Optional<User> user = Optional.ofNullable(getUser());
String result = user
  .map(User::getAddress)
  .map(Address::getStreet)
  .orElse("not specified");

In this example, we used the map() method to convert results of calling the getAdress() to the Optional<Address> and getStreet() to Optional<String>. If any of these methods returned null, the map() method would return an empty Optional.

在这个例子中,我们使用map()方法将调用getAdress()的结果转换为Optional<Address> getStreet()转换为Optional<String> 。如果这些方法中的任何一个返回nullmap()方法将返回一个空的Optional

Now imagine that our getters return Optional<T>.

现在想象一下,我们的getters返回Optional<T>

In this case, we should use the flatMap() method instead of the map():

在这种情况下,我们应该使用flatMap()方法而不是map()

Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
String result = optionalUser
  .flatMap(OptionalUser::getAddress)
  .flatMap(OptionalAddress::getStreet)
  .orElse("not specified");

Another use case of Optional is changing NPE with another exception.

Optional的另一个用例是改变NPE与另一个例外。

So, as we did previously, let’s try to do this in pre-Java 8’s style:

所以,就像我们之前所做的那样,让我们尝试以Java 8之前的风格来做这件事。

String value = null;
String result = "";
try {
    result = value.toUpperCase();
} catch (NullPointerException exception) {
    throw new CustomException();
}

And the answer is more readable and simpler if we use Optional<String>:

而如果我们使用Optional<String>,答案就更易读,更简单。

String value = null;
Optional<String> valueOpt = Optional.ofNullable(value);
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();

Notice that how to use Optional in our app and for what purpose is a serious and controversial design decision, and explanation of all its pros and cons is out of the scope of this article. But there are plenty of interesting articles devoted to this problem. This one and this one could be very helpful to dig deeper.

请注意,如何在我们的应用程序中使用Optional以及出于什么目的,是一个严肃而有争议的设计决定,对其所有利弊的解释超出了本文的范围。但是有很多有趣的文章专门讨论这个问题。这一篇这一篇可能对深入挖掘有很大帮助。

5. Conclusion

5.结论

In this article, we briefly discussed some interesting new features in Java 8.

在这篇文章中,我们简要地讨论了Java 8中一些有趣的新功能。

There are of course many other additions and improvements spread across many Java 8 JDK packages and classes.

当然,还有许多其他的补充和改进,分布在许多Java 8 JDK包和类中。

But the information illustrated in this article is a good starting point for exploring and learning about some of these new features.

但本文所说明的信息是探索和学习其中一些新功能的一个良好起点。

Finally, all the source code for the article is available over on GitHub.

最后,文章的所有源代码都可以在GitHub上找到