Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java is there a static version of 'this'

Tags:

java

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.

like image 526
aronp Avatar asked Jan 25 '11 11:01

aronp


People also ask

Is this static in Java?

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.

Can we use this with static?

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.

Can we 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.

Can you have a static object in Java?

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.


2 Answers

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();
like image 67
dogbane Avatar answered Sep 21 '22 01:09

dogbane


An ugly hack but, this will give you the current class name:

private static String tag = new RuntimeException().getStackTrace()[0].getClassName();

like image 28
J K Avatar answered Sep 21 '22 01:09

J K