aronp
aronp

Reputation: 799

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.

Upvotes: 6

Views: 1084

Answers (6)

denkku
denkku

Reputation: 15

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

Upvotes: 1

J K
J K

Reputation: 1677

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

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

Upvotes: 3

Bert F
Bert F

Reputation: 87573

You don't know how I've wished for something like that (this.class), but sadly, no.

Upvotes: 1

dogbane
dogbane

Reputation: 274758

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();

Upvotes: 7

Péter Török
Péter Török

Reputation: 116286

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 :-)

Upvotes: 2

Nishant
Nishant

Reputation: 55866

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.

Upvotes: 1

Related Questions