Sometimes you really want to track which other methods are calling/invoking a particular method, at runtime. There is a quick and dirty way of doing it that I find pretty nifty and decided to share, in case you are not already familiar with it. In this method, you can track the caller by analyzing the stack trace.

Let’s look at an example. Today I wanted to track who is opening connections to a database in a particular scenario/flow. I created a “proxy” class, intentionally named DriverManager (but not java.sql.DriverManager by my.package.DriverManager) to obscure the “REAL” one and do some monitoring.

Here is the class, and I hope the code is self-explanatory:

public class DriverManager {

    public static Connection getConnection( String uri ) {

        try {
            throw new Exception("GettingStackTrace");
        }   catch ( Exception ex ) {
            StackTraceElement[] elements =  ex.getStackTrace();
            StackTraceElement element = null;

            element = elements[1];
            System.out.println ( "Connection requested from method:"
                    + element.getClassName() +
                    "." + element.getMethodName() );
        }

        Connection con = null;
        try {
            con = java.sql.DriverManager.getConnection(uri);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return con;
    }
}