您当前的位置:首页 > 计算机 > 编程开发 > Java

Java冷知识之——魔数(Magic Number)

时间:06-14来源:作者:点击数:

一、 编程中的魔数

在阿里巴巴Java开发手册编程规约第二节常量定义的第一条中写道:

在这里插入图片描述

魔法值(即魔数)指的是未经预先定义的常量,而反例中的 “Id#taobao_” 则叫做魔字符串(Magic String)。这一规定在《Clean Code》和各大公司的代码规范手册中都有被提及过,那为什么这样规定呢?

《计算机程序的构造和解释》一书中表达过这种观点:

代码的第一要义是供人类理解,其次才是能正确地被机器执行。

没有一个程序猿愿意去读不带注释的代码,注释是一个好东西,但谁愿意为他代码中每一个常量后边加上注释?加得不累?我们看着累!公司里的一个项目基本都是多人合作,多组交接完成,谁也不希望在接手上一任的摊子前先要花几天去读明白他写的代码,因此,良好的代码规范,是每一位程序猿所必要的,用静态变量、枚举、宏定义等方法去避免代码中出现魔数,大大提高代码的可读性,让你的合作伙伴不再动不动就拿着你的小人扎你。

二 、文件中的魔数

文件中的魔数是为了确定文件的类型,许多格式的文件都有魔数,比如bmp中的“BM”、JPEG/JFIF中的“JFIF”,另外一些音频、视频格式的文件一样有魔数,Java也不例外。下面是一个简单的Java文件

public class MagicNumber {
    public static void main(String[] args) {
        System.out.println("Cafe Babe");
    }
}

在当前目录shift+鼠标右键打开 Power Shell,用javac编译该java文件,并在Emacs里按Alt+X输入hexl mode 以16进制模式打开class文件:

在这里插入图片描述

如图

  • 前四个字节cafebabe就是Class文件的魔数
  • 5、6字节为Class文件的次版本号
  • 7、8字节为Class文件的主版本号,0034,即十进制的52.0对应JDK 1.8.0

关于cafebabe,Java的创始人之一,大佬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. 0xCAFEBABE’s decimal number is 3405691582. If we add up all the bits we get 43. Exactly greater than 42-Ultimate Answer to the Life, the Universe, and Everything. The other 43 is also a prime number. You see, magic everywhere. Even in the last sentence.

部分翻译如下:

“我们常去一个叫St Michael’s Alley的地方吃午饭。根据当地的传说,很久以前有个叫Grateful Dead的乐队在成名前常在此演出…我们常去那里,我们把它称作Cafe Dead。我注意到这个名字是一串16进制数,当时我需要一对魔数去表示Class文件和Object文件(对象序列化的文件),我用CAFEDEAD表示object文件,然后把后两个字节替换掉,最后我决定用CAFEBABE表示Class文件…Object 文件被RMI(即远程方法调用)代替,CAFEDEAD也随之而去。0xCAFEBABE的十进制数是3405691582,把每一位加起来得到的是43,恰好大于42——生命、宇宙以及任何事情的终极答案(出自道格拉斯·亚当斯所作的小说《银河系漫游指南》)。另外,43也是个质数(玄学宇宙数论),你看,魔法无处不在,甚至在最后一句”

果然大佬们的脑回路就是不一样,而且这样看来,Java咖啡的命名从这里就有点苗头了。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门