I need to find the caller of a method. Is it possible using stacktrace or reflection?
The calling method is the method that contains the actual call. The called method is the method being called. They are different. They are also called the Caller and the Callee methods. For example int caller(){ int x=callee(); } int callee(){ return 5; }
Getting Name of Current Method inside a method in JavagetEnclosingMethod() returns a Method object representing the immediately enclosing method of the underlying class. StackTraceElement. getMethodName()-The java. lang.
To read this stack trace, start at the top with the Exception's type - ArithmeticException and message The denominator must not be zero . This gives an idea of what went wrong, but to discover what code caused the Exception, skip down the stack trace looking for something in the package com.
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
According to the Javadocs:
The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.
A StackTraceElement
has getClassName()
, getFileName()
, getLineNumber()
and getMethodName()
.
You will have to experiment to determine which index you want (probably stackTraceElements[1]
or [2]
).
Note: if you are using Java 9 or later you should use StackWalker.getCallerClass()
as described in Ali Dehghani's answer.
The comparison of different methods below is mostly interesting for historical reason.
An alternative solution can be found in a comment to this request for enhancement. It uses the getClassContext()
method of a custom SecurityManager
and seems to be faster than the stack trace method.
The following program tests the speed of the different suggested methods (the most interesting bit is in the inner class SecurityManagerMethod
):
/** * Test the speed of various methods for getting the caller class name */ public class TestGetCallerClassName { /** * Abstract class for testing different methods of getting the caller class name */ private static abstract class GetCallerClassNameMethod { public abstract String getCallerClassName(int callStackDepth); public abstract String getMethodName(); } /** * Uses the internal Reflection class */ private static class ReflectionMethod extends GetCallerClassNameMethod { public String getCallerClassName(int callStackDepth) { return sun.reflect.Reflection.getCallerClass(callStackDepth).getName(); } public String getMethodName() { return "Reflection"; } } /** * Get a stack trace from the current thread */ private static class ThreadStackTraceMethod extends GetCallerClassNameMethod { public String getCallerClassName(int callStackDepth) { return Thread.currentThread().getStackTrace()[callStackDepth].getClassName(); } public String getMethodName() { return "Current Thread StackTrace"; } } /** * Get a stack trace from a new Throwable */ private static class ThrowableStackTraceMethod extends GetCallerClassNameMethod { public String getCallerClassName(int callStackDepth) { return new Throwable().getStackTrace()[callStackDepth].getClassName(); } public String getMethodName() { return "Throwable StackTrace"; } } /** * Use the SecurityManager.getClassContext() */ private static class SecurityManagerMethod extends GetCallerClassNameMethod { public String getCallerClassName(int callStackDepth) { return mySecurityManager.getCallerClassName(callStackDepth); } public String getMethodName() { return "SecurityManager"; } /** * A custom security manager that exposes the getClassContext() information */ static class MySecurityManager extends SecurityManager { public String getCallerClassName(int callStackDepth) { return getClassContext()[callStackDepth].getName(); } } private final static MySecurityManager mySecurityManager = new MySecurityManager(); } /** * Test all four methods */ public static void main(String[] args) { testMethod(new ReflectionMethod()); testMethod(new ThreadStackTraceMethod()); testMethod(new ThrowableStackTraceMethod()); testMethod(new SecurityManagerMethod()); } private static void testMethod(GetCallerClassNameMethod method) { long startTime = System.nanoTime(); String className = null; for (int i = 0; i < 1000000; i++) { className = method.getCallerClassName(2); } printElapsedTime(method.getMethodName(), startTime); } private static void printElapsedTime(String title, long startTime) { System.out.println(title + ": " + ((double)(System.nanoTime() - startTime))/1000000 + " ms."); } }
An example of the output from my 2.4 GHz Intel Core 2 Duo MacBook running Java 1.6.0_17:
Reflection: 10.195 ms. Current Thread StackTrace: 5886.964 ms. Throwable StackTrace: 4700.073 ms. SecurityManager: 1046.804 ms.
The internal Reflection method is much faster than the others. Getting a stack trace from a newly created Throwable
is faster than getting it from the current Thread
. And among the non-internal ways of finding the caller class the custom SecurityManager
seems to be the fastest.
As lyomi points out in this comment the sun.reflect.Reflection.getCallerClass()
method has been disabled by default in Java 7 update 40 and removed completely in Java 8. Read more about this in this issue in the Java bug database.
As zammbi has found, Oracle was forced to back out of the change that removed the sun.reflect.Reflection.getCallerClass()
. It is still available in Java 8 (but it is deprecated).
3 years after: Update on timing with current JVM.
> java -version java version "1.8.0" Java(TM) SE Runtime Environment (build 1.8.0-b132) Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode) > java TestGetCallerClassName Reflection: 0.194s. Current Thread StackTrace: 3.887s. Throwable StackTrace: 3.173s. SecurityManager: 0.565s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With