How to get class name only, not full path?
AndroidAndroid Problem Overview
I am aware that using Context
and a method getClass().getName()
I can get a string which represent full class name, like com.package1.package2.MainActivity
.
How can I get only the last part, class name only? In this case it would be MainActivity
string.
I can do it with a simple split()
method, but maybe there is a better way, more reliable.
Android Solutions
Solution 1 - Android
This is all you need.
MainActivity.this.getClass().getSimpleName();
Solution 2 - Android
To get only the name of the class, not full path you will use this expression:
String className = this.getLocalClassName();
//or
String className = getBaseContext().getLocalClassName();
//or
String className = getApplicationContext().getLocalClassName();
Solution 3 - Android
Alternatively, you could use:
private static final String TAG = MainActivity.class.getSimpleName();
Solution 4 - Android
-
If you need class name within a method, use
getLocalClassName()
-
If you need class name outside a method, use
getClass().getSimpleName()
-
If you want to reuse the class name in multiple methods within the same class, then use
private final String TAG = getClass().getSimpleName();
within the class and then use TAG variable in every method. -
If you want to access the class name from static methods, then use
private static final String TAG = MainActivity.class.getSimpleName();
now use the static variable TAG within your static methods.
Solution 5 - Android
No matter what way you do it, you'll need to perform an extra operation on top of getClass. I'd recommend this over split:
String className = xxx.getClass();
int pos = className.lastIndexOf ('.') + 1;
String onlyClass = className.substring(pos);
Solution 6 - Android
Use the getSimpleName
method:
String name = getClass().getSimpleName();
Solution 7 - Android
In kotlin you should use:
val className = javaClass.simpleName
Solution 8 - Android
Kotlin way: MainActivity::class.java.simpleName
Solution 9 - Android
No other solutions work for me, dunno why. I'm using
this.getClass().getName().replace("$",".").split("\\.")[3]
cons: in one string, and you can use it in threads and listeners.
(in listeres I get something like com.djdance.android.main$53)
Solution 10 - Android
If you want to get the name outside the class you can call:
MainActivity.class.getSimpleName()
in this way you can avoid to make your class static.