Java7语法新特性

Java7语法新特性

 

 

电子书下载地址: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();
        }
    }
 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值