tags:

views:

2963

answers:

7

How can one get the name of the class from a static method in that class. For example

public class MyClass {
    public static String getClassName() {
        String name = ????; // what goes here so the string "MyClass" is returned
        return name;
    }
}

To put it in context, I actually want to return the class name as part of a message in an exception.

+10  A: 

How about?

 MyClass.class.getName();
toolkit
If you're going to hard-code in knowledge of MyClass like that, then you might as well just do String name = "MyClass"; !
John Topley
But then, refactoring the class name in your IDE will not work properly.
James Van Huis
True. Although MyClass.class will ensure this line doesn't get forgotten with a 'change class name' refactoring
toolkit
I *wish* "this" worked in a static context to mean the current Class in Java, that that "class.xxx" was allowed in either instance or static code to mean this class! The problem with this is that MyClass is verbose and redundant, in the context. But then as much as I like Java it does seem to lean towards verbosity.
Software Monkey
A: 

If you want the entire package name with it, call:

String name = MyClass.class.getCanonicalName();

If you only want the last element, call:

String name = MyClass.class.getSimpleName();
James Van Huis
+2  A: 

Do what toolkit says. Do not do anything like this:

return new Object() { }.getClass().getEnclosingClass();
Tom Hawtin - tackline
this seems less bad than the SecurityManager or Throwable solutions...
Tetsujin no Oni
There is no arguing with that.
Tom Hawtin - tackline
A: 

This is what I use to grab a named logger without embedding a classname in each class; it could be used to similar effect in your code. Only works on JVM1.4.2 and later.

import org.apache.log4j.Logger;

public class LogService
{
string Logger getLogger(){
Throwable t = new Throwable();
t.fillInStackTrace();
return Logger.getLogger(t.getStackTrace()[1].getClassName());   
}
}
Tetsujin no Oni
This code will fail on some JVMs, notably IBM's JVM for the iSeries, where the stack trace elements include those within the Exception constructor(s).
Software Monkey
That had been mentioned when this was discussed previously... I'll note that it's within the realm of practices discussed on the log4j users list as recently as this year.
Tetsujin no Oni
+1  A: 

Abuse the SecurityManager

System.getSecurityManager().getClassContext()[0].getName();

Or, if not set, use an inner class that extends it (example below shamefully copied from Real's HowTo):

public static class CurrentClassGetter extends SecurityManager {
    public String getClassName() {
        return getClassContext()[1].getName(); 
    }
}
Christoffer
A: 

I use this to init the Log4j Logger at the top of my classes (or annotate).
PRO: Throwable is already loaded and you might save resources by not using the "IO heavy" SecurityManager.
CON: Some question as to whether this will work for all JVMs.
// Log4j . Logger --- Get class name in static context by creating an anonymous Throwable and
// getting the top of its stack-trace.
// NOTE you must use: getClassName() because getClass() just returns StackTraceElement.class
static final Logger logger = Logger.getLogger(new Throwable() .getStackTrace()[0].getClassName());

count ludwig
A: 

This works fine: Thread.currentThread().getStackTrace()[1].getClassName();

Keksi