252

In C# we have Type.FullName and Type.Name for getting the name of a type (class in this case) with or without the namespace (package in java-world).

What is the java equivalent to Type.Name?

Clearly there must be a better way than using Class.getName() and strip it of the package name manually.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Ola Herrdahl
  • 4,216
  • 3
  • 29
  • 23
  • 1
    I did a quick search on this and was not to impressed by the first results that I found on Google so consider this as a freebie. – Ola Herrdahl Apr 22 '10 at 11:31
  • 5
    Forget Google! The **first place to look** for answers about the Java standard class library are the Java API docs (aka javadocs): http://java.sun.com/javase/reference/api.jsp – Stephen C Apr 22 '10 at 12:06
  • For literal answers to the question, see: [How to *really* get the name of a class without the package](https://stackoverflow.com/q/20583164/2402790). – Michael Allan Mar 14 '21 at 02:48

2 Answers2

453

Class.getSimpleName()

Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.

The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

It is actually stripping the package information from the name, but this is hidden from you.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • It also maps the internal name of an anonymous class to an empty String and does stuff with array class names. – Stephen C Apr 22 '10 at 12:03
  • 4
    I didn't know it could return an empty string, and IMHO that's a design flaw. If there is no simple name it should throw an exception. – finnw Apr 22 '10 at 13:20
  • 1
    For inner classes, it strips not only the package but also the outer class' name. (I wanted the other behaviour, so this answer is wrong for me.) – toolforger Aug 31 '20 at 15:53
  • @toolforger Would `this.getClass.getEnclosingClass.getSimpleName + "$" + this.getClass.getSimpleName` work for your purpose? – Alonso del Arte Nov 28 '20 at 23:56
  • 1
    @AlonsodelArte Not sure (there are complications like multiple nesting levels and anonymous classes). Not too relevant anyway, I just wanted to point out that the answer is technically incorrect for the question as written. – toolforger Nov 29 '20 at 14:56
  • @toolforger Yeah, probably not. For my purpose that prompted me to look this up, `getSimpleName()` does just fine. – Alonso del Arte Nov 29 '20 at 23:03
18

If using a StackTraceElement, use:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);
Fidel
  • 7,027
  • 11
  • 57
  • 81