Get a class by name from stack trace

Viewed 770

In a class, I am trying to determine who initially invoked the call chain by using the Thread's stack trace:

StackTraceElement trace = Thread.getStackTrace();
for (int index = 3; index < trace.length; index++ ) {
    String className = trace[index].getClassName();

Now I know that the call will always be initiated by the super type MyObject, but I would like to know which subclass actually started the call for logging / auditing purposes.

I am first trying to see if I can logically match superclasses, but even that is failing; I have tried all 4 of the following, but they all seem to return false:

By single-stepping, I can see that I am in the loop with the proper className which is my child that extends MyObject

    if (Class.forName(className).isAssignableFrom(MyObject.class)) {
    if (MyObject.isAssignableFrom(Class.forName(className))) {

    if (Class.forName(className).instanaceOf(MyObject.class)) {
    if (MyObject.instanaceOf(Class.forName(className))) {

How else could I test if the class name that I have extends a certain parent?

1 Answers

The stacktrace refers each method (class:method:line) that was invoked from the initial thread until the location where you asked the stracktrace.
The stacktrace is designed to understand which code/statements were executed and not to know the runtime class that invoked the method (while you may know it in some circumstances).
In fact you will know the runtime class of the invoked method while it is not inherited or that it is inherited but overrided.
For example if you don't override toString() in Foo, toString() will reference Object.toString() in the stracktrace.

So to achieve your requirement with your actual way, you need to override the entry point of the classes that you want to audit and then invoke super.theMethod().
But a cleaner way is probably using AOP (AspectJ or Spring AOP) to trap any information that you would exploit. For example, in the aspect of auditing entry point methods, you could use getClass() to know the type of the object.

Related