Find in a method being called, which class & method invoked it


package de.eknori.tools;

import java.util.Calendar;

public class CallTrace {

	public void getInfo() {
		Throwable t = new Throwable();
		StackTraceElement[] elements = t.getStackTrace();

	
		StringBuilder sb = new StringBuilder();
		String callingMethodName = elements[2].getMethodName();
		String callingMethodClassName = elements[2].getClassName();
		String calledMethodName = elements[1].getMethodName(); // target
		String calledMethodClassName = elements[1].getClassName();
		sb.append(Calendar.getInstance().getTimeInMillis());
		sb.append(": ");
		sb.append(callingMethodClassName);
		sb.append(".");
		sb.append(callingMethodName);
		sb.append("()");
		sb.append(" --> ");
		sb.append(calledMethodClassName);
		sb.append(".");
		sb.append(calledMethodName);
		sb.append("()");
	

		System.out.println(sb.toString());
	}
}


public class Caller {

	public void methodC1() {
		new CallTrace().getInfo();
	}

	public static void main(String[] args) {

		Caller.foo();

	}
	
	private static void foo(){
		new CallTrace().getInfo();
		Caller.bar();
	}
	
	private static void bar(){
		new CallTrace().getInfo();
		
	}
}

will output

1338006494323: de.eknori.tools.Caller.main() --> de.eknori.tools.Caller.foo()
1338006494323: de.eknori.tools.Caller.foo() --> de.eknori.tools.Caller.bar()
All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.
No comments yetLogin first to comment...