Accessing the class from a static method which the class owns is a bit tricky. From a non-static method accessing the class is as simple as doing this.
// get stack trace StackTraceElement[] stackTrace = new Throwable().getStackTrace(); // get the class name at the top level of the stack trace StackTraceElement stackTraceTopLevelElem = stackTrace[0]; String thisClassName = stackTraceTopLevelElem.getClassName(); // get the class using the class loader Class thisClass; try { thisClass = Class.forName(thisClassName); } catch (ClassNotFoundException exc) { // this should never happen }
The other way is to use Java’s SecurityManager class as described in this article. This way seems preferable because it is not as costly as creating an exception as done in the other way.
Here is some sample code using the SecurityManager. Note that we need to use an inner class because the getClassContext()
method is protected.
public static void main(String[] args) { Class clazz = new ClassGetter().getClazz(); } // inner class is necessary since getClassContext is protected private static class ClassGetter extends SecurityManager { protected ClassGetter() { // do nothing } protected Class getClazz() { Class [] classes = getClassContext(); Class clazz = classes[1]; return clazz; } }