Thursday, January 11, 2007

Invoker class

For a long time I've been thinking how to write code to get the name of the calling class, some days back I was reading an article which arose my curiosity again. I was successful doing it in two ways.

1. Stacktrace method

One of the hints which I got was our exception class, whenever an exception is thrown we get the whole stack strace, which includes the invoking classes.
Throwable t = new Throwable(); 
StackTraceElement callerClass = t.getStackTrace()[1];
System.out.println(callerClass.getClassName());


Gets the class name :)

2. Security Manager method

class SM extends SecurityManager {
@Override
public Class[] getClassContext() {
return super.getClassContext();
}
}



SM sm = new SM();
Class[] classContext = sm.getClassContext();
System.out.println(classContext[2].getName());

Bingo, got the class name. getClassContext() is a protected method, to use it we need to extend security manager or use it as I've done above.

No comments: