Determining the calling context in Java
Here’s a useful little class that will let you determine exactly what function invoked the current function. You might need this for logging sometime. It’s called Trace. Here’s an example usage:
package SomePackage;
import java.io.*;
public class A
{
public static void functionA()
{
System.out.println(”Executing functionA called from ” + Trace.getCallingFunction());
}
public static void functionB()
{
functionA();
}
public static void main(String[] args)
{
functionB();
}
}
Using Trace.java below you should get this output: “Executing functionA called from functionB”
The basic idea is that it constructs an exception and uses the exceptions stack trace to determine the calling function and class (or the current function and class). Here’s the code:
package SomePackage
public class Trace
{
private static StackTraceElement getFunctionName(int depth)
{
StackTraceElement[] funcs = (new ArithmeticException()).getStackTrace();
try
{ return funcs[depth];
}
catch(Exception ex)
{
return null;
}
}
// A function would call one of these three functions to find out
// what function and/or class called it
public static String getCallingClassAndFunction()
{
try
{
StackTraceElement elem = getFunctionName(3);
return elem.getClassName() + “::” + elem.getMethodName();
}
catch(Exception ex)
{
return “”; // In case the current function is main
}
}
public static String getCallingClass()
{
try
{
StackTraceElement elem = getFunctionName(3);
return elem.getClassName();
}
catch(Exception ex)
{
return “”; // In case the current function is main
}
}
public static String getCallingFunction()
{
try
{
StackTraceElement elem = getFunctionName(3);
return elem.getMethodName();
}
catch(Exception ex)
{
return “”; // In case the current function is main
}
}
// A function would call this to get its own name and/or class
public static String getCurrentClassAndFunction()
{
try
{
StackTraceElement elem = getFunctionName(2);
return elem.getClassName() + “::” + elem.getMethodName();
}
catch(Exception ex)
{
return “”; // should never happen
}
}
public static String getCurrentClass()
{
try
{
StackTraceElement elem = getFunctionName(2);
return elem.getClassName();
}
catch(Exception ex)
{
return “”; // should never happen
}
}
public static String getCurrentFunction()
{
try
{
StackTraceElement elem = getFunctionName(2);
return elem.getMethodName();
} catch(Exception ex)
{
return “”; // should never happen
}
}
}
Leave a Reply

