# Java教程 - Java7新特性

介绍一下 Java7 中新增的常用的新特性。

# 1.1 switch中选择因子支持String类型

以前switch中选择因子只能使用number或enum,Java7开始支持String类型。

String value = "abc";
switch (value) {
	case "abc":
		break;
	case "bcd":
		break;
	default:
		break;
}
1
2
3
4
5
6
7
8
9

# 1.2 数字字面量下划线支持

很长的数字可读性不好,在 Java 7中可以使用下划线分隔长 int 以及 long,系统在运算时先去除下划线。

int one_million = 1_000_000;
// 减去11
int value = one_million - 1_1;
1
2
3

# 1.3 泛型实例化类型自动推断

下面的代码:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
1

在 Java 7后,通过类型推断后变成:

Map<String, List<String>> anagrams = new HashMap<>();
1

这个 <> 被叫做 diamond(钻石)运算符,这个运算符从引用的声明中推断类型。

# 1.4 二进制字面量

支持二进制字面值表示,以0b0B开头。

byte b = 0b010;
int i = 0b11;
short s = 0b100;

System.out.println(b); // 2
System.out.println(i); // 3
System.out.println(s); // 4
1
2
3
4
5
6
7

# 1.5 多个异常的合并与重抛异常的检查

很多时候,我们捕获了多个异常,却做了相同的事情,但是却不得不分开处理,显得不优雅。

在之前的版本中:

try {
    //...
}
catch (ArithmeticException e) {
    e.printStackTrace();
}
catch (NullPointerException e) {
    e.printStackTrace();
}
1
2
3
4
5
6
7
8
9

在 JDK1.7版本中,可以合并写成:

try {
    // ...
}
catch (ArithmeticException | NullPointerException e) {
    e.printStackTrace();
}
1
2
3
4
5
6

# 1.6 对资源的自动回收管理

jdk7提供了 try-with-resources ,可以自动关闭相关的资源(只要该资源实现了AutoCloseable接口,jdk7为绝大部分资源对象都实现了这个接口),写在 try() 中的资源才可以自动关闭。

JDK1.7之前的做法,需要在 finally 块中关闭相关资源

String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
	BufferedReader br = new BufferedReader(new FileReader(path));
	try {
		return br.readLine();
	} finally {
		if (br != null) {
			br.close();
		}
	}
}
1
2
3
4
5
6
7
8
9
10

JDK1.7中已经不需要手工关闭这些资源了,JRE自动关闭这些资源。

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    // Exception handling
}
1
2
3
4
5
6
7
8