How to get the name of a class without the package?

Java

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getSimpleName%28%29">`Class.getSimpleName()`</a>

> 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.

Solution 2 - Java

If using a StackTraceElement, use:

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

System.out.println(simpleClassName);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOla HerrdahlView Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavaFidelView Answer on Stackoverflow