In Java is there a static version of 'this'
I know 开发者_如何学编程this is quite minor, but at the top of every class I end up copying and pasting and then changing the following line of code.
private static final String TAG = MyClass.class.getName();
What I would like to do is not to have to modify the MyClass bit every time I copy.
i.e. I would like to write this.
private static final String TAG = this.class.getName();
but clearly there is no this at this point. I know its minor, but I generally learn something from SO answers, and indeed learnt some good stuff just searching to see if there was an answer already.
You can define an Eclipse template, called tag
, for example:
private static final String TAG = ${enclosing_type}.class.getName();
Then, type tag
followed by Ctrl+Space
and it will insert this statement.
I use this method to declare loggers in my classes.
Alternatively, query the stack trace of the current Thread:
private static final String TAG = Thread.currentThread().getStackTrace()[1].getClassName();
An ugly hack but, this will give you the current class name:
private static String tag = new RuntimeException().getStackTrace()[0].getClassName();
Unfortunately there is no way to avoid this. You have to specify the class token for each class explicitly. Reflection could possibly provide some general way to deal with this, but it would be so much more ugly that it is not worth thinking about it :-)
this
stands for instance specific stuffs. For Class level stuffs use class name or just call them explicitly, if you are calling from within the class.
You don't know how I've wished for something like that (this.class
), but sadly, no.
User dogbane suggested querying the stack trace of the current Thread
.
One might move out that code into a class named ClassInfo
:
package util;
public class ClassInfo {
private ClassInfo() {}
static public String className() {
return Thread.currentThread().getStackTrace()[2].getClassName();
}
}
Then, from a static context, we can get the class name by referring to ClassInfo.className()
or simply className()
if we use a static import.
Example:
import static util.ClassInfo.className;
public class MyClass {
public static void main(String[] args) {
System.out.println( className() );
Inner.print();
}
private static class Inner {
static void print() {
System.out.println( className() );
}
}
}
Output:
MyClass MyClass$Inner
精彩评论