How to get class name only, not full path?

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(); 

This is all you need.

MainActivity.this.getClass().getSimpleName();

Alternatively, you could use:

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

  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.

Tags:

Android