Breaking News
Home / Java / Java Snippets / Find the Calling Method in Java?

Find the Calling Method in Java?

StackTrace LookupThis snippet shows how to write a method whoCalledMe() which would be used to find the calling method. This example leverages the fact that the JVM maintains a stack wherein, it adds the method names as they are invoked, so the top method in the stack is one that would have called the current one.

package com.livrona.snippets.util;

/**
 * This snippet shows how to write a method whoCalledMe() to find the calling
 * method that can be used in any method.
 * 
 * @author java4learners
 * 
 */
public class Caller {

	/**
	 * Who Called the method
	 * 
	 * @return
	 */
	public static String whoCalledMe() {
		String retVal = "";
		// The constructor for Throwable has a native function that fills the
		// stack trace.
		java.lang.StackTraceElement[] trace = (new Throwable()).getStackTrace();

		// Once you have the trace you can pick out information you need.
		if (trace.length >= 2) {
			retVal = trace[1].getClassName() + "." + trace[1].getMethodName()
					+ "()";
		}

		return retVal;
	}

	/**
	 * Main method
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(Caller.whoCalledMe());
	}

}

 [pb_builder]

Check Also

How to progamatically get the Java version?

Snippet The key here is to use the system property java.version and get minor and …

Leave a Reply