java是一门开源的程序设计语言,研究源码时,开发者很想debug一下jdk源码。
虽然官方的jdk自带了源码包src.zip,然而在debug时查看变量却十分麻烦。
例如调试Matcher的 boolean search(int from) 方法时,发现一个问题
boolean search(int from) {
this.hitEnd = false;
this.requireEnd = false;
from = from < 0 ? 0 : from;
this.first = from;
this.oldLast = oldLast < 0 ? from : oldLast;
for (int i = 0; i < groups.length; i++)
groups[i] = -1;
acceptMode = NOANCHOR;
boolean result = parentPattern.root.match(this, from, text);
if (!result)
this.first = -1;
this.oldLast = this.last;
return result;
}
单步调试到 this.first = from; 这行代码时发现:
search()方法的入参(arg0)的值为9,from的值为0,from赋值给first之后,this.first=9
这里变量from显示的值明显是不正确的,而且每次进入search方法的时候(无论入参是多少),from的值都为0。
继续调试发现,执行 boolean result = parentPattern.root.match(this, from, text); 查看result的值(ctrl+shift+i)会提示:
可以看到,不能显示result变量的值
原因在于oracle提供的jre中rt.jar不带debug信息.
Oracle在编译src时使用了 javac -g:none,意思是不带任何调试信息,这样可以减小rt.jar的大小。
若想正常调试jdk,就只能重新编译src.zip。
这里介绍下编译src.zip的方法:
1、在eclipse中新建一个java项目“jdk”,然后在src目录上导入"Archive File",选择源码src.zip导入,导完目录结构如下(不用管编译报错):
2、右键项目export...,然后导出为jar包,起名为rt_debug.jar:
3、修改eclipse的jre设置,将rt_debug.jar添加到jre中,并移动到最前面:
4、最后再查看debug变量,可以看到正确的变量值了: