JDK7在语法上的几处小变化

来源:互联网 发布:穿越到唐朝的小说 知乎 编辑:程序博客网 时间:2024/06/06 03:05
转自:http://kenwublog.com/small-language-changes-will-be-jdk7

1,菱形语法(泛型实例化类型自动推断)
List<String> list = new ArrayList<>(); // 这个左右尖括号真的很像菱形

2,在目前版本中,不可具体化的泛型(任意类型)可变参数,在编译时,会在调用处产生警告,JDK7里将这个警告挪到了方法定义处。
变化前:
static <T> List<T> asList(T... elements) { ... }
static List<Callable<String>> stringFactories() {
    Callable<String> a, b, c;
    ...
     // 警告处
    return asList(a, b, c);
  }

变化后:
// 警告处
static <T> List<T> asList(T... elements) { ... }
static List<Callable<String>> stringFactories() {
    Callable<String> a, b, c;
    ...
    return asList(a, b, c);
  }

3,字符串switch
String s = ...
switch(s) {
  case "quux":
    processQuux(s); //没有break,继续往下
 
  case "foo":
  case "bar":
    processFooOrBar(s);
    break;
  case "baz":
     processBaz(s); //没有break,继续往下
 
  default:
    processDefault(s);
    break;
}


4,支持二进制语法和单位级别的数字表示方式。
// 8位byte
byte aByte = (byte)0b00100001;
// 16位short
short aShort = (short)0b1010000101000101;
// 32位int
int anInt1 = 0b10100001010001011010000101000101;
支持单位级别的数字,提高可读性
long underScores = 9_223_372_036_854_775_807L; // 每三位加一下划线,等同于 9,223,372,036,854,775,807


5,从语法层面上支持集合,不再是数组的专利。
final List<Integer> piDigits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9];
final Set<Integer> primes = { 2, 7, 31, 127, 8191, 131071, 524287 };
final Map<Integer, String> platonicSolids = { 4 : "tetrahedron",
6 : "cube", 8 : "octahedron", 12 : "dodecahedron", 20 : "icosahedron"
};


6,JSR 292 动态类型语言支持。
Dynamic x = (动态语言脚本);
Object  y = x.foo("ABC").bar(42).baz();


7,动态资源管理。
在目前版本的java中,当你操作流时,一定会加try..finally以保证出现异常时,流能被正确关闭。
BufferedReader br = new BufferedReader(new FileReader(path));
try {
    return br.readLine();
} finally {
    br.close();
}
在JDK7里,你只需要将资源定义在try()里,Java7就会在readLine抛异常时,自动关闭资源。
另外,资源类必须实现 Disposable 接口。支持管理多个资源。
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
    return br.readLine();
}
原创粉丝点击