1.diamond operator(菱形操作符)
以前代码
Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>>现在可以这样
Map<String, List<Trade>> trades = new TreeMap <> ();可以根据前面的类型推断后面的类型,但<>是必须的
2.Using strings in switch statements
switch语句可以使用stringpublic 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; } }
Automatic resource management
自动关闭资源老代码
public void oldTry() { 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 } } }新特性
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 } }
Improved exception handling
改善异常处理以前代码
public void oldMultiCatch() { try { methodThatThrowsThreeExceptions(); } catch (ExceptionOne e) { // log and deal with ExceptionOne } catch (ExceptionTwo e) { // log and deal with ExceptionTwo } catch (ExceptionThree e) { // log and deal with ExceptionThree } }
改善后
public void newMultiCatch() { try { methodThatThrowsThreeExceptions(); } catch (ExceptionOne | ExceptionTwo | ExceptionThree e) { // log and deal with all Exceptions } }
New file system API (NIO 2.0)
java.nio.file由Path
, Paths
,FileSystem
, FileSystems组成
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()); }
输出为
Number of Nodes:2 File Name:temp.txt File Root:c: File Parent:c:TempFiles.deleteIfExists(path)如果不存在path不抛异常,createSymbolicLink创建符号连(可能相当于linux的软连接吧)
File change notifications
/** * 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; } }
Fork and Join
Fork/Join 模式有自己的适用范围。如果一个应用能被分解成多个子任务,并且组合多个子任务的结果就能够获得最终的答案,那么这个应用就适合用 Fork/Join 模式来解决Supporting dynamism
集成动态语言(ruby,groovy, Python)调用当然现在也可以调用,但是jdk7统一了一个标准,oracle总是在折腾标准