这个特性还是挺有用的,在Java7之前,switch中只允许byte,short,int,char,emun 5种类型,此次加入String也是合情合理。
String s = "a";
switch (s) {
case "a":
System.out.println("is a");
break;
case "b":
System.out.println("is b");
break;
default:
System.out.println("is c");
break;
}
Java7之前我们必须要在try-catch-finally中手动关闭socket、文件、数据库连接等资源,如InputStream,Writes,Sockets,Sql等;Java7中在try语句中申请资源,实现资源的自己主动释放(资源类必须是实现java.lang.AutoCloseable接口或java.io.Closeable接口的对象,一般的文件、数据库连接等均已实现该接口,close方法将被自己主动调用)。并且try语句中支持管理多个资源。
Java7之前:
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(fileName);
br = new BufferedReader(fr);
return br.readLine();
} catch (Exception e) {
log.error("error:{}", e);
} finally {
if (br != null) {
try {
br.close();
} catch(IOException e){
log.error("error:{}", e);
}
}
Java7:
try (
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
) {
return br.readLine();
}catch (Exception e) {
log.error("error:{}", e);
}
这样一来简洁不少。
Java7之前:
try {
result = field.get(obj);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Java7:
try {
result = field.get(obj);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
Java7之前:
public void read(String filename) throws BaseException {
FileInputStream input = null;
IOException readException = null;
try {
input = new FileInputStream(filename);
} catch (IOException ex) {
readException = ex; //保存原始异常
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
if (readException == null) {
readException = ex;
}
}
}
if (readException != null) {
throw new BaseException(readException);
}
}
}
在Java7中能够使用addSuppressed方法记录被抑制的异常:
public void read(String filename) throws IOException {
FileInputStream input = null;
IOException readException = null;
try {
input = new FileInputStream(filename);
} catch (IOException ex) {
readException = ex;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
if (readException != null) { //此处的差别
readException.addSuppressed(ex);
}
else {
readException = ex;
}
}
}
if (readException != null) {
throw readException;
}
}
}
直接上代码把,个人认为意义不太大。
Java7之前:
List<String> list = new ArrayList<String>();
Java7:
List<String> list = new ArrayList<>();
举例:
int binary = 0b0001_1001;
int intOne = 1_000_000;
long longOne = 1_000_000;
double doubleOne = 1_000_000;
float floatOne = 1_000_000;
System.out.println("binary is :"+binary); //25
不太了解
另外还有一些JSR提案的通过,例如:JSR341(EL表达式),JSR292(Invoke Dynamic),JSR203(NIO)。
评论