Java has a static version of 'this'

I know this is pretty minor, but at the top of each class I finish copying and pasting and then changing the next line of code.

private static final String TAG = MyClass.class.getName(); 

What I would like to do is not to change the MyClass bit with every copy.

i.e. I would like to write this.

 private static final String TAG = this.class.getName(); 

but it’s clear that this is not at the moment. I know it is secondary, but I generally learned something from the SO answers, and really found out that some good things are just looking to see if there is an answer already.

+4
source share
6 answers

You can define an Eclipse template called tag , for example:

 private static final String TAG = ${enclosing_type}.class.getName(); 

Then enter tag and then Ctrl+Space , and it will insert this statement.

I use this method to declare loggers in my classes.

Alternatively, request a stack trace of the current thread:

 private static final String TAG = Thread.currentThread().getStackTrace()[1].getClassName(); 
+7
source

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

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

+3
source

Unfortunately, there is no way to avoid this. You must explicitly specify a class token for each class. Reflection could give some general way to handle this, but it would be much more ugly that you should not think about it :-)

+2
source

this means specific instances. For class-level products, use the class name or simply call them explicitly if you are calling from a class.

+1
source

You do not know how I wanted something like this ( this.class ), but unfortunately not.

+1
source

The dogbane user suggested requesting a stack trace of the current Thread . You can move this code to a class called ClassInfo :

 package util; public class ClassInfo { private ClassInfo() {} static public String className() { return Thread.currentThread().getStackTrace()[2].getClassName(); } } 

Then from the static context, we can get the class name by referring to ClassInfo.className() or just className() if we use 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
+1
source

Source: https://habr.com/ru/post/1336946/


All Articles