如何在java中获取一个方法的调用者

public class TestClass {
	public static void main(String[] args)
	{
		TestClass tc = new TestClass();
		tc.test();
	}

	public void test()
	{
		MethodTest mt = new MethodTest();
		mt.getCaller();
	}

}
class MethodTest{
	public void getCaller()
	{
		StackTraceElement stack[] = (new Throwable()).getStackTrace();
		for (int i = 0; i < stack.length; i++)
		{
			StackTraceElement s = stack[i];
			System.out.format(" ClassName:%d\t%s\n", i, s.getClassName());
			System.out.format("MethodName:%d\t%s\n", i, s.getMethodName());
			System.out.format("  FileName:%d\t%s\n", i, s.getFileName());
			System.out.format("LineNumber:%d\t%s\n\n", i, s.getLineNumber());
		}
	}
}

猜你喜欢

转载自my.oschina.net/lizongyue/blog/1631397
今日推荐