最终变量在 jshell 中无法正常运行

标签 final java-9 access-modifiers 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 时,上述警告非常明显。详细模式如下:

enter image description here

关于最终变量在 jshell 中无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47880733/

相关文章:

dns - Java 9 中是否有 com.sun.jndi.dns.DnsContextFactory 的替代品?

java - transient 如何在序列化 Java 中与 final 一起工作

java - 自定义 String 类创建

java - static 和 Final 对包意味着什么?

方法局部类中的 Java 最终静态声明

java - 如何解决java.lang.NoClassDefFoundError : javax/xml/bind/JAXBException

java-9 - JShell 访问在 jshell 实例之外定义的变量

java - 访问修饰符在封装中有什么作用吗

有引用时可以访问 Java 私有(private)字段吗?

Java - 子类中的 protected 变量是什么类型?