getting only name of the class Class.getName()

JavaClass

Java Problem Overview


How can i get the name of the class

String.class.getName()  returns java.lang.String


I am only interested in getting last part ie only String
Any Api can do that?

Java Solutions


Solution 1 - Java

Solution 2 - Java

The below both ways works fine.

System.out.println("The Class Name is: " + this.getClass().getName());
System.out.println("The simple Class Name is: " + this.getClass().getSimpleName());

Output as below:

> The Class Name is: package.Student > > The simple Class Name is: Student

Solution 3 - Java

or programmaticaly

String s = String.class.getName();
s = s.substring(s.lastIndexOf('.') + 1);

Solution 4 - Java

You can use following simple technique for print log with class name.

private String TAG = MainActivity.class.getSimpleName();

Suppose we have to check coming variable value in method then we can use log like bellow :

private void printVariable(){
Log.e(TAG, "printVariable: ");
}

Importance of this line is that, we can check method name along with class name. To write this type of log.

write :- loge and Enter.

will print on console

E/MainActivity: printVariable:

Solution 5 - Java

Social.class.getSimpleName()

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 "[]".

Solution 6 - Java

Here is the Groovy way of accessing object properties:

this.class.simpleName    # returns the simple name of the current class

Solution 7 - Java

Get simple name instead of path.

String onlyClassName =  this.getLocalClassName(); 

call above method in onCreate

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
QuestionakshayView Question on Stackoverflow
Solution 1 - JavaandybView Answer on Stackoverflow
Solution 2 - JavaVenkatesh KView Answer on Stackoverflow
Solution 3 - JavaMauricio QuintanaView Answer on Stackoverflow
Solution 4 - JavaKailas BhakadeView Answer on Stackoverflow
Solution 5 - JavaLSD25View Answer on Stackoverflow
Solution 6 - Javaeaglet3dView Answer on Stackoverflow
Solution 7 - JavaZar E AhmerView Answer on Stackoverflow