为什么jshell允许在lambda表达式中使用非final自由变量?



.java文件中,以下内容将无法编译:

class Test {
public static void main(String[] args) {
int x = 0;
Runnable r = () -> System.out.println(x);
r.run();
x++;
r.run();
}
}

然而,在jshell中,这将工作,第一个r.run()的输出是0,第二个1。所以我想知道x如何访问r?

jshell的实际工作方式:

class $1 { int x; static void run() { x = 0; } }
class $2 { Runnable r; static void run() { r = () -> print($1.x); } }
class $3 { static void run() { $2.r.run(); } }
class $4 { static void run() { $1.x++; } }
class $5 { static void run() { $2.r.run(); } }

每次你输入一个新的命令,jshell定义一个新的类,并把它包装成一个静态方法。

您可以使用new Throwable().printStackTrace() 查看实际的类名

最新更新