[阅读笔记] Java 7 新特性

来源:互联网 发布:死亡真面目知乎 编辑:程序博客网 时间:2024/05/02 01:40

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 trades = new treemap ();

(since 7) map 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用来对动态语言进行支持。要了解这个特性需要找专门的资料。


======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/