Sharing of new features in Java 8 that may have been overlooked
When it comes to Java 8, you can only hear lambda, but this is just one of them. Java 8 also has many new features, some powerful new classes or new usages, and some functions. It should have been added to Java a long time ago, so the following article mainly introduces you to some new features in Java8 that you may have overlooked. Friends in need can refer to it.
Preface
We have previously introduced the relevant content about lambda and functional programming in Java8. Although we have started the journey of Java8, But many people started using Java 8 directly from Java 6. There may be some features of JDK7 that you don’t know yet. In this chapter, we will take you to review those features that we have forgotten. Although we can't talk about all the features at once, we can pick out the commonly used core features and learn them together.
Exception improvements
##try-with-resources
This feature appeared in JDK7. When we operated a stream object before, it was probably like this:1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 |
|
Using multiple resources
##
1 2 3 4 5 6 |
|
Of course if you are using a non-standard library The class can also customize AutoCloseable, as long as its close method is implemented.
Catch multiple ExceptionsWhen we operate an object, sometimes it will throw multiple exceptions, like this:
1 2 3 4 5 6 7 8 |
|
This code requires catching a lot of exceptions, which is not very elegant. JDK7 allows you to catch multiple exceptions:
1 2 3 4 5 6 |
|
And the exception parameter after the catch statement is final and cannot be modified/copied.
Handling reflection exceptionsStudents who have used reflection may know that we sometimes throw many irrelevant checks when operating reflection methods Exceptions, for example:
1 2 3 4 5 6 7 8 9 10 |
|
Although you can use the catch multiple exception method to catch all the above exceptions, it is also painful. JDK7 fixed this defect and introduced a new class ReflectiveOperationException to help you catch these reflection exceptions:
1 2 3 4 5 6 |
|
File Operation We know that in JDK6 or even before, it was very troublesome for us to read a text file, but now they have become simple, thanks to NIO2, let's take a look first Previous approach:
Read a text file1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Everyone must be familiar with such a piece of code, but this is too It’s cumbersome. I just want to read a text file. I have to write so much code and deal with a bunch of headache-inducing exceptions. No wonder others complain that Java is bloated, but I’m losing. . .
Now I will introduce how to improve these problems in JDK7.
PathPath is used to represent file paths and files. Similar to the File object, the Path object does not necessarily correspond to an actual existence. file, which is just an abstract sequence of paths.
There are many ways to create a Path object. The first is the two static methods of the final class Paths. How to construct a Path object from a path string:
1 2 3 4 |
|
Constructed through FileSystems
1 |
|
Conversion between Path, URI and File
1 2 3 4 |
|
Read and write files
You can use the Files class to quickly implement file operations, such as reading file contents:
1 2 |
|
If you want to read by line To get a file, you can call
1 |
|
. On the contrary, if you want to write a string to a file, you can call
1 |
|
. You can also write files line by line. The parameters of the Files.write method support passing a class instance that implements the Iterable interface. To append content to a specified file, you can use the third parameter OpenOption of the write method:
1 2 |
|
By default, all methods in the Files class will operate using UTF-8 encoding. When you don't want to do this, you can pass the Charset parameter to change it.
Of course there are some other common methods for Files:
1 2 3 4 |
|
Create, move, delete
Create files and directories
1 2 3 4 |
|
Files also provides some methods for us to create temporary files/temporary directories:
1 2 3 4 |
|
这里的dir是一个Path对象,并且字符串prefix和suffix都可能为null。 例如调用Files.createTempFile(null, ".txt")
会返回一个类似/tmp/21238719283331124678.txt
读取一个目录下的文件请使用Files.list
和Files.walk
方法
复制、移动一个文件内容到某个路径
1 2 |
|
删除一个文件
1 |
|
小的改进
Java8是一个较大改变的版本,包含了API和库方面的修正,它还对我们常用的API进行很多微小的调整, 下面我会带你了解字符串、集合、注解等新方法。
字符串
使用过JavaScript语言的人可能会知道当我们将一个数组中的元素组合起来变成字符串有一个方法join, 例如我们经常用到将数组中的字符串拼接成用逗号分隔的一长串,这在Java中是要写for循环来完成的。
Java8种添加了join方法帮你搞定这一切:
1 |
|
第一个参数是分隔符,后面接收一个CharSequence类型的可变参数数组或一个Iterable。
集合
集合改变中最大的当属前面章节中提到的Stream API,除此之外还有一些小的改动。
类/接口 | 新方法 |
---|---|
Iterable | foreach |
Collection | removeIf |
List | replaceAll, sort |
Map | forEach, replace, replaceAll, remove(key, value), putIfAbsent, compute, computeIf, merge |
Iterator | forEachRemaining |
BitSet | stream |
Map中的很多方法对并发访问十分重要,我们将在后面的章节中介绍
Iterator提供forEachRemaining将剩余的元素传递给一个函数
BitSet可以产生一个Stream对象
通用目标类型判断
Java8对泛型参数的推断进行了增强。相信你对Java8之前版本中的类型推断已经比较熟悉了。 比如,Collections中的方法emptyList方法定义如下:
1 |
|
emptyList方法使用了类型参数T进行参数化。 你可以像下面这样为该类型参数提供一个显式的类型进行函数调用:
1 |
|
不过编译器也可以推断泛型参数的类型,上面的代码和下面这段代码是等价的:
1 |
|
我还是习惯于这样书写。
注解
Java 8在两个方面对注解机制进行了改进,分别为:
可以定义重复注解
可以为任何类型添加注解
重复注解
之前版本的Java禁止对同样的注解类型声明多次。由于这个原因,下面的第二句代码是无效的:
1 2 3 4 5 6 |
|
我们之前可能会通过数组的做法绕过这一限制:
1 2 3 4 5 6 7 8 |
|
Book类的嵌套注解相当难看。这就是Java8想要从根本上移除这一限制的原因,去掉这一限制后, 代码的可读性会好很多。现在,如果你的配置允许重复注解,你可以毫无顾虑地一次声明多个同一种类型的注解。 它目前还不是默认行为,你需要显式地要求进行重复注解。
创建一个重复注解
如果一个注解在设计之初就是可重复的,你可以直接使用它。但是,如果你提供的注解是为用户提供的, 那么就需要做一些工作,说明该注解可以重复。下面是你需要执行的两个步骤:
将注解标记为@Repeatable
提供一个注解的容器下面的例子展示了如何将@Basic注解修改为可重复注解
1 2 3 4 5 6 7 8 |
|
完成了这样的定义之后,Person类可以通过多个@Basic注解进行注释,如下所示:
1 2 3 |
|
编译时, Person 会被认为使用了 @Basics( { @Basic(name="fix") , @Basic(name="todo")} )
这样的形式进行了注解,所以,你可以把这种新的机制看成是一种语法糖, 它提供了程序员之前利用的惯用法类似的功能。为了确保与反射方法在行为上的一致性, 注解会被封装到一个容器中。 Java API中的getAnnotation(Class<T> annotationClass)
方法会为注解元素返回类型为T的注解。 如果实际情况有多个类型为T的注解,该方法的返回到底是哪一个呢?
我们不希望一下子就陷入细节的魔咒,类Class提供了一个新的getAnnotationsByType方法, 它可以帮助我们更好地使用重复注解。比如,你可以像下面这样打印输出Person类的所有Basic注解:
返回一个由重复注解Basic组成的数组
1 2 3 4 5 6 |
|
Null检查
Objects类添加了两个静态方法isNull和nonNull,在使用流的时候非常有用。
例如获取一个流的所有不为null的对象:
1 2 3 |
|
Optional
空指针异常一直是困扰Java程序员的问题,也是我们必须要考虑的。当业务代码中充满了if else判断null 的时候程序变得不再优雅,在Java8中提供了Optional类为我们解决NullPointerException。
我们先来看看这段代码有什么问题?
1 2 3 4 5 6 7 8 9 |
|
这段代码看起来很正常,每个User都会有一个名字。所以调用getUserName方法会发生什么呢? 实际这是不健壮的程序代码,当User对象为null的时候会抛出一个空指针异常。
我们普遍的做法是通过判断user != null然后获取名称
1 2 3 4 5 6 |
|
但是如果对象嵌套的层次比较深的时候这样的判断我们需要编写多少次呢?难以想象
处理空指针
使用Optional优化代码
1 2 3 4 |
|
当user为null的时候我们设置UserName的值为null,否则返回getName的返回值,但此时不会抛出空指针。
在之前的代码片段中是我们最熟悉的命令式编程思维,写下的代码可以描述程序的执行逻辑,得到什么样的结果。 后面的这种方式是函数式思维方式,在函数式的思维方式里,结果比过程更重要,不需要关注执行的细节。程序的具体执行由编译器来决定。 这种情况下提高程序的性能是一个不容易的事情。
我们再次了解下Optional中的一些使用方法
Optional方法
创建 Optional 对象
你可以通过静态工厂方法Optional.empty,创建一个空的Optional对象:
1 |
|
创建一个非空值的Optional
1 |
|
如果user是一个null,这段代码会立即抛出一个NullPointerException,而不是等到你试图访问user的属性值时才返回一个错误。
可接受null的Optional
1 |
|
使用静态工厂方法Optional.ofNullable
,你可以创建一个允许null值的Optional对象。
如果user是null,那么得到的Optional对象就是个空对象,但不会让你导致空指针。
使用map从Optional对象中提取和转换值
1 2 |
|
这种操作就像我们之前在操作Stream是一样的,获取的只是User中的一个属性。
默认行为及解引用Optional对象
我们决定采用orElse方法读取这个变量的值,使用这种方式你还可以定义一个默认值, 遭遇空的Optional变量时,默认值会作为该方法的调用返回值。 Optional类提供了多种方法读取 Optional实例中的变量值。
get()
是这些方法中最简单但又最不安全的方法。如果变量存在,它直接返回封装的变量 值,否则就抛出一个NoSuchElementException异常。所以,除非你非常确定Optional 变量一定包含值,否则使用这个方法是个相当糟糕的主意。此外,这种方式即便相对于 嵌套式的null检查,也并未体现出多大的改进。orElse(T other)
是我们在代码清单10-5中使用的方法,正如之前提到的,它允许你在 Optional对象不包含值时提供一个默认值。orElseGet(Supplier<? extends T> other)
是orElse方法的延迟调用版,Supplier 方法只有在Optional对象不含值时才执行调用。如果创建默认值是件耗时费力的工作, 你应该考虑采用这种方式(借此提升程序的性能),或者你需要非常确定某个方法仅在 Optional为空时才进行调用,也可以考虑该方式(这种情况有严格的限制条件)。orElseThrow(Supplier<? extends X> exceptionSupplier)
和get方法非常类似, 它们遭遇Optional对象为空时都会抛出一个异常,但是使用orElseThrow你可以定制希 望抛出的异常类型。ifPresent(Consumer<? super T>)
让你能在变量值存在时执行一个作为参数传入的 方法,否则就不进行任何操作。
当前除了这些Optional类也具备一些和Stream类似的API,我们先看看Optional类方法:
方法 | 描述 |
---|---|
empty | 返回一个空的 Optional 实例 |
get | 如果该值存在,将该值用Optional包装返回,否则抛出一个NoSuchElementException异常 |
ifPresent | 如果值存在,就执行使用该值的方法调用,否则什么也不做 |
isPresent | 如果值存在就返回true,否则返回false |
filter | 如果值存在并且满足提供的谓词,就返回包含该值的 Optional 对象; 否则返回一个空的Optional对象 |
map | 如果值存在,就对该值执行提供的 mapping 函数调用 |
flatMap | 如果值存在,就对该值执行提供的 mapping 函数调用, 返回一个 Optional 类型的值,否则就返 回一个空的Optional对象 |
of | 将指定值用 Optional 封装之后返回,如果该值为null,则抛出一个NullPointerException异常 |
ofNullable | 将指定值用 Optional 封装之后返回,如果该值为 null,则返回一个空的Optional对象 |
orElse | 如果有值则将其返回,否则返回一个默认值 |
orElseGet | 如果有值则将其返回,否则返回一个由指定的 Supplier 接口生成的值 |
orElseThrow | 如果有值则将其返回,否则抛出一个由指定的 Supplier 接口生成的异常 |
用Optional封装可能为null的值
目前我们写的大部分Java代码都会使用返回NULL的方式来表示不存在值,比如Map中通过Key获取值, 当不存在该值会返回一个null。 但是,正如我们之前介绍的,大多数情况下,你可能希望这些方法能返回一个Optional对象。 你无法修改这些方法的签名,但是你很容易用Optional对这些方法的返回值进行封装。
我们接着用Map做例子,假设你有一个Map<String, Object>
类型的map,访问由key的值时, 如果map中没有与key关联的值,该次调用就会返回一个null。
1 |
|
使用Optional封装map的返回值,你可以对这段代码进行优化。要达到这个目的有两种方式: 你可以使用笨拙的if-then-else判断语句,毫无疑问这种方式会增加代码的复杂度; 或者你可以采用Optional.ofNullable
方法
1 |
|
每次你希望安全地对潜在为null的对象进行转换,将其替换为Optional对象时,都可以考虑使用这种方法。
总结
The above is the detailed content of Sharing of new features in Java 8 that may have been overlooked. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the "Share to" option at the bottom, and then select the first "WeChat Moments" allows you to share content to WeChat Moments.

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the "Shared Members" column 】, and finally check all

Mango TV has various types of movies, TV series, variety shows and other resources, and users can freely choose to watch them. Mango TV members can not only watch all VIP dramas, but also set the highest definition picture quality to help users watch dramas happily. Below, the editor will bring you some free Mango TV membership accounts for users to use, hurry up and take a look Take a look. Mango TV latest member account free sharing 2023: Note: These are the latest member accounts collected, you can log in directly and use them, do not change the password at will. Account number: 13842025699 Password: qds373 Account number: 15804882888 Password: evr6982 Account number: 13330925667 Password: jgqae Account number: 1703

Understand the key features of SpringMVC: To master these important concepts, specific code examples are required. SpringMVC is a Java-based web application development framework that helps developers build flexible and scalable structures through the Model-View-Controller (MVC) architectural pattern. web application. Understanding and mastering the key features of SpringMVC will enable us to develop and manage our web applications more efficiently. This article will introduce some important concepts of SpringMVC

Title: To solve the problem that Discuz WeChat shares cannot be displayed, specific code examples are needed. With the development of the mobile Internet, WeChat has become an indispensable part of people's daily lives. In website development, in order to improve user experience and expand website exposure, many websites will integrate WeChat sharing functions, allowing users to easily share website content to Moments or WeChat groups. However, sometimes when using open source forum systems such as Discuz, you will encounter the problem that WeChat shares cannot be displayed, which brings certain difficulties to the user experience.

HP printers are essential printing equipment in many offices. Installing the printer driver on the computer can perfectly solve problems such as the printer being unable to connect. So how to install HP printer driver? The editor below will introduce you to two HP printer driver installation methods. The first method: download the driver from the official website 1. Search the HP China official website in the search engine, and in the support column, select [Software and Drivers]. 2. Select the [Printer] category, enter your printer model in the search box, and click [Submit] to find your printer driver. 3. Select the corresponding printer according to your computer system. For win10, select the driver for win10 system. 4. After downloading successfully, find it in the folder

People in the workplace will be familiar with PPT production, because whether it is a year-end summary or a work report, many companies require it to be presented in the form of PPT. At this time, I encountered a problem, that is, how to share PPT? Don’t worry, the editor below will show you how to share PPT. 1. First select the edited PPT and click Save in the upper left corner (if you are using WPS, you can click Login first). 2. Then click the share icon in the menu bar as shown below. 3. Then the sharing interface as shown below will pop up. You can see that a sharing link will appear. Click to send the link to share. 4. You can also click "Allow friends to edit" in the lower left corner of the picture below, so that friends can also click to edit this PPT. 5. If necessary, give P
