[阅读笔记] Java 7 新特性

Time: 1.5 hours
原文:A look at Java 7's new features, by Madhusudhan Konda
http://radar.oreilly.com/2011/09/java7-features.html

1. 引入了"Diamond Operator"(写法:<>)

一句话描述:简化创建参数化类的对象的语法。
示例
(before 7) Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>> ();
(since 7) Map<String, List<Trade>> trades = new TreeMap <> ();
注意点
trades = new TreeMap () 也是合法的,但是编译器会提示"type-safety warnings"
Comment
Java 7以前要避免这种繁琐的语法,要借用static factory method来实现;《Effective Java 2nd》 Item 1中对此进行过说明, Joshua在书中提到"Someday the language may perform this sort of type inference on constructor invocations as well as method invocations.",果不其然,现在这个版本里就支持了这个特性。

2. Switch支持String类型

一句话描述:无。
示例:无:
注意点:判断case是否相等时调用String.equals()方法进行比较。
Comment
1. 这样switch支持的类型有:primitive types, enum, string
2. 使用string比enum更容易出错,降低出错风险的手段:(1) 将string定义为常量,在case里仅用常量来引用字符串 (2) 如果业务逻辑允许,default语句要毫不犹豫地抛出异常。

3. Automatic resource management

一句话描述try-finally的替代品,用于确保资源被释放。
示例
(before 7)
try {
fos = new FileOutputStream("movies.txt"); dos = new DataOutputStream(fos); dos.writeUTF("Java 7 Block Buster"); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); dos.close(); } catch (IOException e) { // log the exception } } (since 7) try (FileOutputStream fos = new FileOutputStream("movies.txt");
DataOutputStream dos = new DataOutputStream(fos)) { dos.writeUTF("Java 7 Block Buster");
} catch (IOException e) { // log the exception

              }

注意点
1. 放在这个结构里的资源必须要实现java.lang.AutoCloseable接口(这个接口仅有一个close方法)
2. 印象中C#里早就有类似的特性
3. 观察示例中的代码,(before 7)的版本里有两个IOException 的catch 语句,对应两个不同场景,因此在catch语句块里有不同的处理逻辑;
但(since 7)仅有一个catch,如何区分不同的情形?需要检查一下编译后的字节码确认一下

4.带下划线的数字
一句话描述:看很长的数字更方便。
示例:int million = 1_000_000
Comment: 对这个特性是否会被开发人员广泛接受表示怀疑。

5. 对异常处理机制的改进
一句话描述:
可以合并多个catch块。
示例
        try {
                  methodThatThrowsThreeExceptions();
            } catch (ExceptionOne | ExceptionTwo | ExceptionThree e) {
               
  // log and deal with all Exceptions
            }
Comment
可以将处理逻辑一样的Exception写到一起,减少代码冗余

6. New file system API (NIO 2.0)

一句话描述:使开发支持多文件系统的代码更加轻松。
新的内容包括:1. java.nio.file,新的类包括Path, Paths, FileSystem, FileSystems等;2. File Change notifacation

7. Fork and Join

一句话描述:将任务分给多个core执行,然后汇总
说明:简单认识相关的几个类
ForkJoinPool:    用以执行ForkJoinTask,实现了Executor, ExecutorService。
ForkJoinTask:    待求解的问题/任务。
RecursiveAction:    ForkJoinTask的子类,不返回值。
RecursiveTask:    ForkJoinTask的子类,返回值。
Executor:        被ForkJoinPool所实现。

8. Supporting dynamism (invokedynamic)

一句话描述:提供对动态语言的支持。
说明:根据类型检查是在编译还是运行时进行,可分为"static typed language"(如Java)和"dynamically typed language"(如Ruby, Python, Clojure)。Java 7中有一个新的包java.lang.invoke用来对动态语言进行支持。要了解这个特性需要找专门的资料。

原文地址:https://www.cnblogs.com/yuquanlaobo/p/2248477.html