Tim Tim - 4 months ago 31
Android Question

android java dot class syntax MainActivity.class.getSimpleName();

I keep coming across this syntax and I have been unable to find any explanation for it.

private static final String TAG = MainActivity.class.getSimpleName();
Log.i(TAG,”some log statement”);

What is the
keyword in

Does this create an inline method called
that is added to the
? if so can someone explain this well enough for me to be able to start using it in my code? Or if someone will point me in the right direction where I can find some documentation to look over.

A full picture of how this code could look and be used

public class MainActivity extends AppCompatActivity {

//What does "class" in the following MainActivity.class.getSimpleName();
private static final String TAG = MainActivity.class.getSimpleName();

protected void onCreate(Bundle savedInstanceState) {

Log.i(TAG, "onCreate()");


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

Just gets the "simple name" of the class MainActivity, which happens to be "MainActivity". One could just write

private static final String TAG = "MainActivity";

as well, but if you later decide to rename the class, you'll have to take care to also change that string constant because no compiler will tell you if you forget it.

Note that SomeClass.class gives you an object which describes the class itself, see https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html.

As such, Someclass.class.getSimpleName() is rarely useful except for logging. However, if you have an object, you can find information about its type by calling someObject.getClass(). This gives you the Class of the object which you can then use to query about the properties of the object's type, e.g. which methods are declared or what the full class name (getCanonicalName()) is.

In Java, this technique is called "reflection". Read more about it e.g. here, or here.