How to get only the class name and not the full path?

I know that using Context and the getClass().getName() method, I can get a string that represents the fully qualified name of the class, for example com.package1.package2.MainActivity .

How can I get only the last part, only the class name? In this case, it will be the MainActivity string.

I can do this with a simple split() method, but maybe there is a better way, more reliable.

+47
android
May 15 '12 at 17:53
source share
7 answers

That is all you need.

 MainActivity.this.getClass().getSimpleName(); 
+115
May 15 '12 at 18:58
source share

To get only the class name and not the full path, you will use this expression:

 String className = this.getLocalClassName(); //or String className = getBaseContext().getLocalClassName(); //or String className = getApplicationContext().getLocalClassName(); 
+14
May 15 '12 at 17:59
source share

Alternatively you can use:

 private static final String TAG = MainActivity.class.getSimpleName(); 
+4
Nov 24 '15 at 21:32
source share

No matter how you do it, you need to do an extra operation on top of getClass. I would recommend this for a split:

 String className = xxx.getClass(); int pos = className.lastIndexOf ('.') + 1; String onlyClass = className.substring(pos); 
+1
May 15 '12 at 17:56
source share
  • If you need the class name inside the method, use getLocalClassName()

  • If you need a class name outside the method, use getClass().getSimpleName()

  • If you want to reuse the class name in several methods within the same class, use private final String TAG = getClass().getSimpleName(); inside the class, and then use the TAG variable in each method.

  • If you want to access the class name from static methods, use private static final String TAG = MainActivity.class.getSimpleName(); Now use TAG static variables in your static methods.

+1
Dec 28 '17 at 9:01
source share

No other solutions work for me, I don’t know why. I use

 this.getClass().getName().replace("$",".").split("\\.")[3] 

cons: on one line, and you can use it in streams and listeners.

(in listeres, I get something like com.djdance.android.main $ 53)

0
Mar 16 '17 at 13:56 on
source share

If you want to get a name outside the class, you can call:

 MainActivity.class.getSimpleName() 

this way you can avoid a static static class.

0
Dec 05 '17 at 7:24
source share



All Articles