static version of getClass()

Posted on Juni 24, 2010, under java.

It is very easy to get the current class if you have an instance of it just by instance.getClass(), but what if you are inside a static method and you have no instance? After I spent some time thinking about this problem, I came up with the following solution:

public static Class<?> getClassStatic()
{
    // get the current thread's stacktrace
    StackTraceElement[] stacktrace
        = Thread.currentThread().getStackTrace();

    // get the class name of the calling method's class
    // 2, because 0 is getStackTrace() and 1 is getClassStatic()
    String className = stacktrace[2].getClassName();

    try
    {
        // get the class instance for the given class name
        return Class.forName(className);
    }
    catch (ClassNotFoundException e)
    {
        // will never be the case, but ClassNotFoundException
        // is checked, thus we have to catch it.
        return null;
    }
}

This solution uses the current Thread’s stacktrace to get the class name of the current class and afterwards it uses Class.forName(…) to get the instance of the class. Not very beautiful, but it works.

Leave a Comment