如果你写了一个超级复杂超级大的项目,在项目后期调试修改的时候,突然想知道到底是哪些类调用了ImportantClass中的Important方法,你会怎么做呢?
首先,你可能说:我用不到!如果这样的话,到这里你就可以return了。
做法一:最常规有效的做法,使用IDE的全目录全文搜索方法名。当然这样是最有效快速的。但是如果有很多别的类中也定义了Important方法,你就会得到很多垃圾搜索结果。同时你只能搜索到目录下的结果,而对于运行时调用Important方法的地方你就无所适从了。
做法二:这就是我要说的,编写程序,获取方法调用者。最直观的例子就是我们每天都在用了log4j。在执行log.debug或者别的输出日至的操作的时候,它都会按照设定的格式输出类名、方法名、甚至所在的行数。如果我们在Important方法中插入这么一段,就可以知道到底是谁在运行期调用了Important方法了。
在demo程序中有详细的注释和一个完整的例子。我们知道把那段代码拷贝到关系的程序中,修改一下fullClassName就可以了。
1 /**
2 * @author zangmeng
3 *
4 *
5 * 如果我们注意观察一下异常时的输出,我们就知道java调用栈的结构了
6 * 最后被调用的方法在栈顶。
7 * 我们这个方法的工作过程就是首先得到调用栈,然后从栈顶向下搜索
8 * 直到搜索到我们关心的Important类。
9 * 然后,在这个类的方法后面的,就是我们关心的Important类的important方法的调用者了
10 * 这时候我们检测第一个不是Important类的类,则这个类必定是调用Important类中
11 * important方法的类和方法。
12 * 然后我们将之打印出来,就可以了。
13 * 同样的道理,我们也可以得到更上一层的调用关系。
14 * 一直追述到线程的启动方法。
15 *
16 */
17 public class Important {
18 public void important() {
19 String fullClassName = "Important";
20 // 首先得到调用栈
21 StackTraceElement stack[] = (new Throwable()).getStackTrace();
22 // 然后从栈中向上搜索,直到搜索到我们的Important类。
23 int ix = 0;
24 while (ix < stack.length) {
25 StackTraceElement frame = stack[ix];
26 String cname = frame.getClassName();
27 if (cname.equals(fullClassName)) {
28 break;
29 }
30 ix++;
31 }
32 // 此时ic位置放置的是Important类。
33 while (ix < stack.length) {
34 StackTraceElement frame = stack[ix];
35 String cname = frame.getClassName();
36 if (!cname.equals(fullClassName)) {
37 //第一个费Important类的类就是调用者
38 System.out.println("调用者此方法的类名:"+cname);
39 System.out.println("在"+cname+"中调用次方法的方法名:"+frame.getMethodName());
40 }
41 ix++;
42 }
43 /**
44 * some important operation is followed :)
45 */
46
47 System.out.println("__This is an important method,and I care for the infor of the invoker!__");
48 }
49 }
摘自:http://www.cnblogs.com/deepnighttwo/archive/2006/08/04/1964313.html