I was digging around in some JVM classes and encountered an interesting way to look up the call stack. Normally you would need to create a stack trace from an exception like this:
public static void bar() {
System.out.println("Bar was called by: " +
(new Throwable()).getStackTrace()[1].getClassName());
}
That's safe and portable but also slow and ugly. You can get some nice debugging information, potentially, but you can't can't the actual class object. On the other hand, there is sun.reflect.Reflection.getCallerClass(), which gives you the actual class very easily:
public static void foo() {
System.out.println("Foo was called by: " +
sun.reflect.Reflection.getCallerClass(2));
}
That's entirely proprietary to the Sun JVM and subject to change at any release. but, it's nice to have around as a quick hack if you need it. The argument to the method specifies how far up the stack trace to look, starting with the Reflection class at 0. So, the current class is 1. The calling class is 2, etc...