Java - get the current class name?

Solution 1:

Try,

String className = this.getClass().getSimpleName();

This will work as long as you don't use it in a static method.

Solution 2:

The "$1" is not "useless non-sense". If your class is anonymous, a number is appended.

If you don't want the class itself, but its declaring class, then you can use getEnclosingClass(). For example:

Class<?> enclosingClass = getClass().getEnclosingClass();
if (enclosingClass != null) {
  System.out.println(enclosingClass.getName());
} else {
  System.out.println(getClass().getName());
}

You can move that in some static utility method.

But note that this is not the current class name. The anonymous class is different class than its enclosing class. The case is similar for inner classes.

Solution 3:

Try using this this.getClass().getCanonicalName() or this.getClass().getSimpleName(). If it's an anonymous class, use this.getClass().getSuperclass().getName()

Solution 4:

You can use this.getClass().getSimpleName(), like so:

import java.lang.reflect.Field;

public class Test {

    int x;
    int y;  

    public String getClassName() {

        String className = this.getClass().getSimpleName(); 
        System.out.println("Name:" + className);
        return className;
    }

    public Field[] getAttributes() {

        Field[] attributes = this.getClass().getDeclaredFields();   
        for(int i = 0; i < attributes.length; i++) {
            System.out.println("Declared Fields" + attributes[i]);    
        }

        return attributes;
    }

    public static void main(String args[]) {

        Test t = new Test();
        t.getClassName();
        t.getAttributes();
    }
}

Solution 5:

The combination of both answers. Also prints a method name:

Class thisClass = new Object(){}.getClass();
String className = thisClass.getEnclosingClass().getSimpleName();
String methodName = thisClass.getEnclosingMethod().getName();
Log.d("app", className + ":" + methodName);