Martin
Martin

Reputation: 3753

Java reflection via a stack trace

In Java, one can write code such as the following to interrogate the stack:

StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for (StackTraceElement frame : stack) {
    System.out.println(frame.getClassName() + "." + frame.getMethodName());
}

Is it possible to get a reflective view of the stack, where rather than just getting the names of the classes and methods, I instead get Class and Method instances? If two methods in a class share a name (with different parameters), can I distinguish between them on the stack?

Upvotes: 1

Views: 885

Answers (2)

Stephen C
Stephen C

Reputation: 718886

Is it possible to get a reflective view of the stack, where rather than just getting the names of the classes and methods, I instead get Class and Method instances?

You can get Class instances by calling Class.forName on the class strings; see Matt Ball's answer. (Nested / inner / anonymous classes might be a bit more tricky ...)

If two methods in a class share a name (with different parameters), can I distinguish between them on the stack?

Only if you have the source code, your application is compiled with debug info, and it is able to parse it to figure out which line numbers correspond to which method overloads. The last is going to be a lot of work to implement, and computationally expensive.

(There is a theoretical problem with this approach too. It is possible to write Java source code with multiple method overloads on one line. If you did that, it would not be possible to distinguish the methods from the information in the stacktrace.)

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359836

The Class bit is easy. Use Class.forName(String):

StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for (StackTraceElement frame : stack) {
    String fqcn = frame.getClassName();
    Class<?> clazz = Class.forName(fqcn);
}

If two methods in a class share a name (with different parameters), can I distinguish between them on the stack?

I don't think so, since the method name returned by StackTraceElement#getMethodName() does not contain parameter number & type information, which is what you'd need to distinguish between methods with the same name.

Upvotes: 2

Related Questions