java获取方法调用者信息的例子

public class T2 {

    
    public void t2Method(){
        getCaller();
    }
    public  void  getCaller(){   
           StackTraceElement stack[] = Thread.currentThread().getStackTrace();  
           for (StackTraceElement ste:stack){   
            if((ste.getClassName().indexOf("T1"))!=-1){
                System.out.println(
"called by "+ste.getClassName()+"."+ste.getMethodName()+"/"+ste.getFileName());
            }
           }   
         }  

}

public class T1 {

    
    public static void main(String[] args) {
        new T2().t2Method();

    }

}



public static void getCaller() {
	StackTraceElement[] stack = (new Throwable()).getStackTrace();
	for (int i = 0; i < stack.length; i++) {
		StackTraceElement ste = stack[i];
		System.out.println(ste.getClassName() + "." + ste.getMethodName() + "(...);");
		System.out.println(i + "--" + ste.getMethodName());
		System.out.println(i + "--" + ste.getFileName());
		System.out.println(i + "--" + ste.getLineNumber());
	}
}


运行显示:
called by com.test.T1.main/T1.java

转自 http://www.blogjava.net/freeman1984/archive/2010/01/14/309413.html
http://www.iteye.com/topic/13179

你可能感兴趣的:(java,thread,html,.net)