本文介绍的java 7新特性更多的感受像是语法糖。毕竟java自己已经比较完善了,不完善的不少比较难实现或者是依赖于某些底层(例如操做系统)的功能。不过java7也实现了相似aio的强大功能。但本文并未有此介绍。主要是 1.switch能够接受string类型而不像之前仅仅是int;2.异常catch能够一次处理完而不像之前一层层的surround;3.泛型类实例化也不用繁琐的将泛型声明再写一遍;4.文件读写 会自动关闭流而不像之前那样须要在finally中显式close;5.数值能够使用下划线分隔;6.文件读写功能加强,有更简单的api调用;7.文件改变的事件通知功能;8.多核 并行计算的支持增强 fork join 框架;9.还有一些动态特性的加入。html
具体看代码:java
1.switch能够接受string类型而不像之前仅仅是int;api
public void processTrade(Trade t) { String status = t.getStatus(); switch (status) { case NEW: newTrade(t); break; case EXECUTE: executeTrade(t); break; case PENDING: pendingTrade(t); break; default: break; } }2.异常catch能够一次处理完而不像之前一层层的surround;
public void newMultiCatch() { try { methodThatThrowsThreeExceptions(); } catch (ExceptionOne | ExceptionTwo | ExceptionThree e) { // log and deal with all Exceptions } }
3.泛型类实例化也不用繁琐的将泛型声明再写一遍;框架
Map<String, List<Trade>> trades = new TreeMap <> ();
public void newTry() { try (FileOutputStream fos = new FileOutputStream("movies.txt"); DataOutputStream dos = new DataOutputStream(fos)) { dos.writeUTF("Java 7 Block Buster"); } catch (IOException e) { // log the exception } }
5.数值能够使用下划线分隔;ide
int million = 1_000_000
6.文件读写功能加强,有更简单的api调用;操作系统
public void pathInfo() { Path path = Paths.get("c:\\Temp\\temp"); System.out.println("Number of Nodes:" + path.getNameCount()); System.out.println("File Name:" + path.getFileName()); System.out.println("File Root:" + path.getRoot()); System.out.println("File Parent:" + path.getParent()); //这样写不会抛异常 Files.deleteIfExists(path); }
7.文件改变的事件通知功能;code
/** * This initiates the police */ private void init() { path = Paths.get("C:\\Temp\\temp\\"); try { watchService = FileSystems.getDefault().newWatchService(); path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } catch (IOException e) { System.out.println("IOException"+ e.getMessage()); } } /** * The police will start making rounds */ private void doRounds() { WatchKey key = null; while(true) { try { key = watchService.take(); for (WatchEvent<?> event : key.pollEvents()) { Kind<?> kind = event.kind(); System.out.println("Event on " + event.context().toString() + " is " + kind); } } catch (InterruptedException e) { System.out.println("InterruptedException: "+e.getMessage()); } boolean reset = key.reset(); if(!reset) break; } }
8.多核 并行计算的支持增强 fork join 框架;htm
ForkJoinPool pool = new ForkJoinPool(numberOfProcessors); public class MyBigProblemTask extends RecursiveAction { @Override protected void compute() { . . . // your problem invocation goes here } } pool.invoke(task);
9.还有一些动态特性的加入。事件
java.lang.invoke
包的引入。 MethodHandle
, CallSite
还有一些其余类供使用。get
具体参见原文 http://radar.oreilly.com/2011/09/java7-features.html