java magic翻譯系列文章,java小伙伴不知道的奇妙世界
Java Magic. Part 2: 0xCAFEBABE
@(Base)[JDK, magic, 黑魔法]
轉載請寫明:原文地址
英文原文
系列文章:
-Java Magic. Part 1: java.net.URL
-Java Magic. Part 2: 0xCAFEBABE
-Java Magic. Part 3: Finally
-Java Magic. Part 4: sun.misc.Unsafe
你知道所有的java class文件都有一個相同的4位元組串嗎。這個4位元組串的16進位是CAFEBABE
。
我們可以簡單編寫一個Hello.java
來驗證一下:
public class Hello {
public static void main(String[] args) {
System.out.println("Hell, O'World!");
}
}
我們用javac
編譯該文件。然後用Emacs打開這個class文件(使用M-x hexl-mode
)來查看,我們得到如下信息:
00000000: cafe babe 0000 0033 001d 0a00 0600 0f09 .......3........
00000010: 0010 0011 0800 120a 0013 0014 0700 1507 ................
00000020: 0016 0100 063c 696e 6974 3e01 0003 2829 .....<init>...()
00000030: 5601 0004 436f 6465 0100 0f4c 696e 654e V...Code...LineN
00000040: 756d 6265 7254 6162 6c65 0100 046d 6169 umberTable...mai
00000050: 6e01 0016 285b 4c6a 6176 612f 6c61 6e67 n...([Ljava/lang
// others..
根據白皮書的規範,前四個位元組(u4)cafebabe就是Class文件的魔數,第5、6位元組(u2)是Class文件的次版本號,第7、8位元組(u2)是主版本號。十六進位0和33,也就是版本號為51.0。
有趣的就是這個4位元組魔數,根據James Gosling的博客,他是這麼解釋的:
We used to go to lunch at a place called St Michael's Alley. According to local legend, in the deep dark past, the Grateful Dead used to perform there before they made it big. It was a pretty funky place that was definitely a Grateful Dead Kinda Place. When Jerry died, they even put up a little Buddhist-esque shrine. When we used to go there, we referred to the place as Cafe Dead. Somewhere along the line it was noticed that this was a HEX number. I was re-vamping some file format code and needed a couple of magic numbers: one for the persistent object file, and one for classes. I used CAFEDEAD for the object file format, and in grepping for 4 character hex words that fit after "CAFE" (it seemed to be a good theme) I hit on BABE and decided to use it. At that time, it didn't seem terribly important or destined to go anywhere but the trash-can of history. So CAFEBABE became the class file format, and CAFEDEAD was the persistent object format. But the persistent object facility went away, and along with it went the use of CAFEDEAD - it was eventually replaced by RMI.
以前我們曾去過一個叫StMichael's Alley
的地方吃中午飯。根據當地一個傳說,在很久很久以前,一個叫做Grateful Dead的樂隊在成名之前一直都在這裡表演。當樂隊成員Jerry死了之後,這裡還一度變成紀念他的地方。我註意到這個地方寫著一串16進位的魔術(這尼瑪明明是個咖啡館的名字好嗎)。當時我正在改造一些文件的格式,我當時需要2個魔術:一個是用來表示object file
,另外一個用來表示class文件。我選擇使用CAFEDEAD
來表示object file,然後把後面2個位元組換掉之後用來表示class文件。我突然想到BABE(小孩的意思)這個放在CAFE的後面應該不錯。當時看來這個東西好像並不是特別重要啦~所以,結果就是你們現在看到的CAFEDEAD
用來表示持久化的object format(也就是object序列化之後的結果),然後CAFEBABE就用來表示class文件。當時persistence object的最終被RMI(java遠程調用)替換掉了,CAFEDEAD
也就不復存在了。
0xCAFEBABE
的十進位是3405691582
。如果我們把所有位加起來得到43。恰好大於42-Ultimate Answer to the Life, the Universe, and Everything。另外43也是一個質數。You see, magic everywhere. Even in the last sentence.
這個作者腦子有點毛病..