最终字段的setter方法 [英] Setter methods for final fields

查看:137
本文介绍了最终字段的setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用反射以及 http://docs.oracle所提供的安装程序中安装的JDK中提供的src.zip .com ,我发现以下字段 java.lang.System

Using reflection and also from the src.zip available in the installed JDK by the installer purveyed by http://docs.oracle.com, I found the following fields of java.lang.System,

out & 错误被宣布为最终版,但他们有各自的(公共)setter方法,这些方法反过来调用他们各自的本地couter-part。

in, out & err are declared as final, but they have respective (public) setter methods which in turn invoke their respective native couter-part.

例如,我可以成功地将控制台输出重定向到文件。

For example, I could successfully re-direct console output to a file.

我们可以在Java代码中初始化后设置最终变量。

We can set final variables exactly once we have initialized it in the Java code.

我的问题是:这个最终规则不适用于本机代码吗?

My question is : is this rule of final not applicable to the native code?

推荐答案


我的问题是:这个最终规则不适用于本机代码吗?

My question is : is this rule of final not applicable to the native code?

本机代码可以破坏 final 的规则。它还可以打破访问规则和基本类型安全以及其他各种因素。

Native code can break the rules on final. It can also break the access rules and basic type safety, and various other things.

关于 final 字段的观点在JLS中实际上不识别实际上是不可变的:请参阅 JLS 17.5.3 。这样做的要点是,如果您确实更改了 final (例如通过反射),则某些保证不再成立。并且更改代表编译时常量的 final 的值可能完全没有效果。

The point about final fields not actually being immutable is actually recognized in the JLS: see JLS 17.5.3. The gist of this is that if you do change a final (via reflection for example), certain guarantees no longer hold. And changing the value of a final that represents a compile time constant is liable to have no effect at all.

但正如@ignis指出的那样, System.in/out/err 在JLS中被特别提及为写保护(JLS 17.5.4 )而不是正常的最终语义。基本上,这意味着 final 保证执行保持,即使变量已更改。

But as @ignis points out, System.in/out/err get special mention in the JLS as being "write-protected" (JLS 17.5.4) rather than having the normal final semantics. Basically, this means that the final guarantees do hold even if the variables are changed.


为什么变量在最终会有一个setter时是最终的?

why have the variables to be final when there will be a setter anyways?

在这种特殊情况下,1)防止 System.in/out/err 被意外分配所破坏,2)所以可以通过 SecurityManager 来控制更改。

In this particular case it is 1) to prevent System.in/out/err from being clobbered by an accidental assignment, and 2) so that changes can be controlled by the SecurityManager.

这篇关于最终字段的setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆