77

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.

4

10 回答 10

176

This is all you need.

MainActivity.this.getClass().getSimpleName();
于 2012-05-15T18:58:15.427 回答
21

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(); 
于 2012-05-15T17:59:26.843 回答
7

Alternatively, you could use:

private static final String TAG = MainActivity.class.getSimpleName();
于 2015-11-24T21:32:29.677 回答
2
  1. If you need class name within a method, use getLocalClassName()

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

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

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

于 2017-12-28T09:01:08.670 回答
1

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);
于 2012-05-15T17:56:52.600 回答
1

Kotlin way: MainActivity::class.java.simpleName

于 2020-09-21T07:13:07.680 回答
0

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)

于 2017-03-16T13:56:33.743 回答
0

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.

于 2017-12-05T07:24:48.007 回答
0

Use the getSimpleName method:

String name = getClass().getSimpleName();
于 2019-12-06T17:15:11.970 回答
0

In kotlin you should use:

val className = javaClass.simpleName
于 2020-04-04T17:52:55.910 回答