Java 7 的 7 个新的 “酷” 特性
Java 7 即将在本月底发布了,先来看 Java 7 中的一些不错的新酷特性吧:
1. switch 中使用字符串变量
public void testStringSwitch(String direction) { switch (direction) { case "up": y--; break; case "down": y++; break; case "left": x--; break; case "right": x++; break; default:System.out.println("Invalid direction!"); break; }}
// Java 7 以前版本Map<String,Map<String,int>>m=new HashMap<String, Map<String,int>>();// Java 7Map<String, Map<String, int>> m = new HashMap<>();
try { Class a = Class.forName("wrongClassName"); Object instance = a.newInstance();} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) { System.out.println("Failed to create instance");}
try (BufferedReader in=new BufferedReader(new FileReader("test.txt"))){ String line = null; while ((line = in.readLine()) != null) {System.out.println(line); }} catch (IOException ex) { ex.printStackTrace();}
List<String> lines = Files.readAllLines(FileSystems.getDefault().getPath("test.txt"), StandardCharsets.UTF_8);for (String line : lines) System.out.println(line);