最终变量在 jshell 中运行不正常

final variables are not functioning well in jshell

我正在使用 JDK9 的 jshell。

我刚刚创建了一个最终变量并为其赋值。 在下一行中,我刚刚修改了值。令我惊讶的是,修改最终变量时没有错误。

这是代码片段:

jshell> final int r = 0;
|  Warning:
|  Modifier 'final'  not permitted in top-level declarations, ignored
|  final int r = 0;
|  ^---^
r ==> 0

jshell> r = 1;
r ==> 1

jshell> System.out.println("r = "+r)
r = 1

这是jshell所期望的吗?或者有一些其他方法可以在 jshell 中使用最终变量?

虽然不应该在顶层创建最终变量。但我想没有什么硬性方法可以限制这种用法。

来自 JShell.eval

周围的文档

The modifiers public, protected, private, static, and final are not allowed on op-level declarations and are ignored with a warning.

Synchronized, native, abstract, and default top-level methods are not allowed and are errors.

If a previous definition of a declaration is overwritten then there will be an event showing its status changed to OVERWRITTEN, this will not occur for dropped, rejected, or already overwritten declarations.

当您在详细模式下执行 jshell 时,上述警告非常明显: