357

All I am trying to do is to get the current class name, and java appends a useless non-sense $1 to the end of my class name. How can I get rid of it and only return the actual class name?

String className = this.getClass().getName();
David
  • 208,112
  • 36
  • 198
  • 279
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • 2
    Where are you calling this? Is it from within an anonymous inner class? Could you add some more code that shows details about the definition of the class and where this line is being called from? – plainjimbo Jun 07 '11 at 20:50
  • 9
    So, all you want is `String className = getClass().getName().substring(0, getClass().getName().indexOf("$"))` – josh.trow Jun 07 '11 at 21:01
  • 12
    If you get `$1` then, because the name of the class is `$1`. If you expect something else, use `this` in the right class instead of the wrong one. – ceving Sep 26 '14 at 13:06

12 Answers12

326

Try,

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

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

jesg
  • 3,285
  • 1
  • 13
  • 2
  • 2
    Actually, no this won't work. This question indicates he has an anonymous inner class, and for this case, getSimpleName() returns `""` – vikingsteve Dec 05 '13 at 08:18
  • 78
    Even though this does not answer the question, this SO post is currently in the top results for "get class name java" on google, and so it is still helpful to the community. – EdgeCaseBerg Oct 10 '14 at 16:52
  • 13
    It will return name without package namespace. Good one! – Oleg Abrazhaev Jan 25 '16 at 10:56
  • For how to get the class name in a static method [see this answer](https://stackoverflow.com/a/29477085/4850949). – not2savvy Jan 26 '23 at 14:01
292

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 5
    But what if the enclosing class is also an anonymous inner class? Don't you have to recursively get the enclosing class until it returns `null`, and use the last non-`null` class you got? – Garret Wilson Jan 07 '15 at 16:15
35

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

Manoj Selvin
  • 2,247
  • 24
  • 20
MirroredFate
  • 12,396
  • 14
  • 68
  • 100
  • Actually, it does. Depending. If you are trying to get the name of the abstract class you are implementing with an anonymous class, this is what you use. – MirroredFate Jun 07 '11 at 21:04
  • for his case (anonymous class), the simple name is empty, the canconical name is null and the superclass is Object. – Bozho Jun 07 '11 at 21:07
  • Yes, yes, no. My first two were just guesses, the third, however, is correct. An anonymous class is a subclass of the class it implements. That's why they work. Thus, the superclass is the abstract class. – MirroredFate Jun 07 '11 at 21:09
  • Weird isn't the super class the class you are inheriting from? Handler is not Inheriting form my class, it's just a member – aryaxt Jun 07 '11 at 21:15
  • Umm... I have tested this, and I get that the superclass of the anonymous class is the abstract class. I will recheck my logic... but as I am getting the result that makes sense, I don't think it's me that has made the mistake.... – MirroredFate Jun 07 '11 at 21:33
  • Ahh, you're probably using "this" while I am using the actual anonymous class variable (whatever it is). When you say "this", you are referring to the object where it is being executed, not the anonymous class itself. – MirroredFate Jun 07 '11 at 21:45
16

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();
    }
}
Vineeth Chitteti
  • 1,454
  • 2
  • 14
  • 30
Karuna
  • 719
  • 1
  • 11
  • 22
4

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);
SoftDesigner
  • 5,640
  • 3
  • 58
  • 47
3

this answer is late, but i think there is another way to do this in the context of anonymous handler class.

let's say:

class A {
    void foo() {
        obj.addHandler(new Handler() {
            void bar() {
                String className=A.this.getClass().getName();
                // ...
            }
        });
    }
}

it will achieve the same result. additionally, it's actually quite convenience since every class is defined at compile time, so no dynamicity is damaged.

above that, if the class is really nested, i.e. A actually is enclosed by B, the class of B can be easily known as:

B.this.getClass().getName()
Jason Hu
  • 6,239
  • 1
  • 20
  • 41
3

Here is a Android variant, but same principle can be used in plain Java too.

private static final String TAG = YourClass.class.getSimpleName();
private static final String TAG = YourClass.class.getName();
Ako
  • 956
  • 1
  • 10
  • 13
2

In your example, this probably refers to an anonymous class instance. Java gives a name to those classes by appending a $number to the name of the enclosing class.

tonio
  • 10,355
  • 2
  • 46
  • 60
1

I'm assuming this is happening for an anonymous class. When you create an anonymous class you actually create a class that extends the class whose name you got.

The "cleaner" way to get the name you want is:

If your class is an anonymous inner class, getSuperClass() should give you the class that it was created from. If you created it from an interface than you're sort of SOL because the best you can do is getInterfaces() which might give you more than one interface.

The "hacky" way is to just get the name with getClassName() and use a regex to drop the $1.

trutheality
  • 23,114
  • 6
  • 54
  • 68
0

In my case, I use this Java class:

private String getCurrentProcessName() {
    String processName = "";
    int pid = android.os.Process.myPid();
    
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
        if (processInfo.pid == pid) {
            processName = processInfo.processName;
            break;
        }
    }
    
    return processName;
}
Albert Khang
  • 621
  • 6
  • 17
-2

I've found this to work for my code,, however my code is getting the class out of an array within a for loop.

String className="";

className = list[i].getClass().getCanonicalName();

System.out.print(className); //Use this to test it works
Tigran Saluev
  • 3,351
  • 2
  • 26
  • 40
hransom
  • 11
  • 1
  • This doesn't add anything that any of the other answers haven't already said. The whole loop/array issue is irrelevant. Also, you should look into how the code formatting works on questions/answers. – Jonathon Reinhart May 01 '14 at 02:43
-4

Reflection APIs

There are several Reflection APIs which return classes but these may only be accessed if a Class has already been obtained either directly or indirectly.

Class.getSuperclass()
     Returns the super class for the given class.

        Class c = javax.swing.JButton.class.getSuperclass();
        The super class of javax.swing.JButton is javax.swing.AbstractButton.

        Class.getClasses()

Returns all the public classes, interfaces, and enums that are members of the class including inherited members.

        Class<?>[] c = Character.class.getClasses();

Character contains two member classes Character.Subset and
Character.UnicodeBlock.

        Class.getDeclaredClasses()
         Returns all of the classes interfaces, and enums that are explicitly declared in this class.

        Class<?>[] c = Character.class.getDeclaredClasses();
     Character contains two public member classes Character.Subset and Character.UnicodeBlock and one private class

Character.CharacterCache.

        Class.getDeclaringClass()
        java.lang.reflect.Field.getDeclaringClass()
        java.lang.reflect.Method.getDeclaringClass()
        java.lang.reflect.Constructor.getDeclaringClass()
     Returns the Class in which these members were declared. Anonymous Class Declarations will not have a declaring class but will

have an enclosing class.

        import java.lang.reflect.Field;

            Field f = System.class.getField("out");
            Class c = f.getDeclaringClass();
            The field out is declared in System.
            public class MyClass {
                static Object o = new Object() {
                    public void m() {} 
                };
                static Class<c> = o.getClass().getEnclosingClass();
            }

     The declaring class of the anonymous class defined by o is null.

    Class.getEnclosingClass()
     Returns the immediately enclosing class of the class.

    Class c = Thread.State.class().getEnclosingClass();
     The enclosing class of the enum Thread.State is Thread.

    public class MyClass {
        static Object o = new Object() { 
            public void m() {} 
        };
        static Class<c> = o.getClass().getEnclosingClass();
    }
     The anonymous class defined by o is enclosed by MyClass.
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
arunkumar sambu
  • 653
  • 1
  • 9
  • 22