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.
Output. The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method.
No, we can't use “this” keyword inside a static method. “this” refers to current instance of the class. But if we define a method as static , class instance will not have access to it, only CLR executes that block of code. Hence we can't use “this” keyword inside static method.
In order to call a static method or property within another static method of the same class, you can use the this keyword.
Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class in which the nested class is defined is known as the Outer Class. Unlike top-level classes, Inner classes can be Static.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With