作者AmosYang (LetMeGoogleThatForYou)
看板java
标题Re: [闲聊] 魔法 JNI
时间Fri Apr 30 17:01:50 2010
※ 引述《AmosYang (LetMeGoogleThatForYou)》之铭言:
: 推 costbook:这种好东西竟然开放下载耶,感谢分享 04/30 08:30
Java 比 .Net 好就好在这些文件整理得好,在官方网站上就可轻易找到
: 推 zanyking:C#里就很直接的给你unsafe区块,等於是挖个窗口直接做 04/30 09:53
C# 比 Java 好就好在比较务实,以 developer 为中心
(唯一一点遗憾的就是没有像 Java 的 throws …至少 make it optional...
让想用的人去用,不想用的人就不要用…)
: 推 james732:感谢分享 很棒的资料!! 04/30 10:30
不客气
: → sbrhsieh:实际上JVM本身就没有enforce final field 的不变性质在.. 04/30 15:43
: → sbrhsieh:定义该 field 的 class 内。 04/30 15:44
: → sbrhsieh:final field setter method 可以在 bytecode level 实现 04/30 15:46
sbrhsieh 提出的这点倒让我想起来一些更有趣的事,
根据我的记忆,在 JDK 1.1, 1.2, 1.3, 1.4, 1.5 ... 一路发展下来
有一段时间其实 final field 可以用 reflection 去改其 value
接下来几个版本又不能改
然後再下来几个版本又变回可以改
现在最新的 Java 6 里可以不可以改…我不知道…有空的人可以试一试
刚去问某 Java 强者这到底是在搞什麽鬼
他说有兴趣的话去看
JSR-000133 Java Memory Model and Thread Specification
里面有一章专门讲 final field
我懒得去看了…有兴趣的人请自行取用 XD
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 65.87.177.87
※ 编辑: AmosYang 来自: 65.87.177.87 (04/30 17:03)
顺藤摸瓜又摸出这个
http://www.javaspecialists.eu/archive/Issue096.html
文章有点旧,但无损其价值,
可以从 "Java 5 - "final" is not final anymore" 读起
摘录最重要的一段
(给与我一样懒得去读JSR133的人…XD)
When Narve Saetre mailed me that he managed to change a final field in JDK
5 using reflection, I was hoping that a bug had crept into the JDK.
However, we both felt that to be unlikely, especially such a fundamental
bug. After some searching, I found the
JSR-133: Java Memory Model and
Thread Specification. Most of the specification is hard reading, and
reminds me of my university days (I used to write like that ;-) However,
JSR-133 is so important that it should be required reading for all Java
programmers. (Good luck)
Start with chapter 9 Final Field Semantics, on page 25. Specifically,
read section 9.1.1 Post-Construction Modification of Final Fields. It
makes sense to allow updates to final fields. For example, we could
relax the requirement to have fields non-final in JDO.
If we read section 9.1.1 carefully, we see that we should only modify
final fields as part of our construction process. The use case is where
we deserialize an object, and then once we have constructed the object,
we initialise the final fields, before passing it on. Once we have made
the object available to another thread, we should not change final
fields using reflection. The result would not be predictable.
It even says this: If a final field is initialized to a compile-time
constant in the field declaration, changes to the final field may not
be observed, since uses of that final field are replaced at compile
time with the compile-time constant. This explains why our iq field
stays the same, but country changes.
※ 编辑: AmosYang 来自: 65.87.177.87 (04/30 17:33)
※ 编辑: AmosYang 来自: 65.87.177.87 (04/30 17:33)