jdk1.8匿名内部类可以访问非final外部变量

之前在1.6的环境下写直接使用外部变量编译器会提示必须要有final修饰,《Think in java》有这一段:

If you’re defining an anonymous inner class and want to use an object that’s defined outside the anonymous inner class, the compiler requires that the argument reference be final, as you see in the argument to destination( ). If you forget, you’ll get a compile-time error message.

但是今天在1.8上尝试发现好像没有这种限制了,可以使用外部值:

        String str = "think";
        System.out.println(new ArrayList<String>() {
            private static final long serialVersionUID = 1L;
            {
                add("a");
                add("23");
                add(str);
            }
        });

能输出

猜你喜欢

转载自blog.csdn.net/u013146766/article/details/79169528
今日推荐