电子书下载地址:http://www.infoq.com/cn/minibooks/know-more-about-java7
电子书并不完整,把第一章整理了一下.
/**
* 增强的可变参数,@SafeVarargs,@SafeVarargs代替@SuppressWarnings("unchecked")
*/
@SafeVarargs
public static <T> T testArgs(T... args) {
return args[0];
}
/**
* 二进制字面变量,0b或0B 标识二进制数字类似(0,0x)
*/
public static void testBinary() {
logger.info(0b1010101);// 85
logger.info(0B1010101);
}
/**
* 增强数字,数字中允许出现"_",来分割数字
*/
public static void testNumber() {
logger.info("number : " + 98_5_6 + 1_2_3.6_95);
}
/**
* 增强switch,允许switch中使用String
*/
public static void testSwitch() {
String str = "good";
switch (str) {
case "good":
logger.info("say good for switch");
}
}
/**
* 增强的try-catch.1,catch可以捕捉多个异常,此时e为异常.2,java.lang.Throwable.addSuppressed方法可以精确抛出异常
*/
public static void testThrowException() {
try {
testThrowException();
} catch (NullPointerException | IndexOutOfBoundsException | NumberFormatException e) {
// catch (FileNotFoundException | IOException e)//系统生成的代码出错,不明白为什么
// java.lang.Throwable.addSuppressed 精确抛出异常
e.addSuppressed(new Exception("测试 void java.lang.Throwable.addSuppressed(Throwable exception)"));
logger.error(e.getClass());
logger.error("测试异常:", e.fillInStackTrace());
}
}
public static void testThrowExceptionA() {
throw new NullPointerException("Throw By void com.henglu.study.Test.throwExceptionTest()");
}
/**
* 增强的try,实现 java.lang.AutoCloseable接口的类可以使用try-with-resources,自动释放资源
*/
public static void testTry() throws IOException {
// 实现 java.lang.AutoCloseable接口的类可以使用try-with-resource,自动释放资源,interface Closeable extends AutoCloseable
try (FileInputStream fileInputStream = new FileInputStream("/nullFile")) {
fileInputStream.read();
}
}