Re: Get the "source" class



Carsten H. Pedersen wrote:
I want to get a hold of the "calling" class of a method / constructor. An example would be as follows:

public class A() {
public A() {
new B();
}
}

public class B() {
public B() {
[stuff here]
}
}

If i replace [stuff here] with System.out.print(getClass().getName()), i would get "B" printed. But i'm interested in getting a hold of A - the instance isn't necessary... the name of the class will do just fine. I suspect it can be done, since the stacktrace of exceptions contain pretty much the information i want.

Anyone have a solution to this problem?

Alas, i was too quick in giving up. I found some pointers, and i've found a solution to the problem. If anyone is interested, this is what i put in to replace [stuff here]:

StackTraceElement[] ste = new Throwable().getStackTrace();
if (ste.length > 1) {
System.out.println("Class: "+ste[1].getClassName());
}
.



Relevant Pages