.class syntax MainActivity.class.getSimpleName();

android, java

Solution

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

Maybe also note that, as a 'normal' programmer, you don't need to know much about reflection beyond the `instanceof` operator. However, some frameworks depend heavily on reflection. Java Persistency API (JPA) providers, for instance, or dependency injection (DI) frameworks; actually, most tools you control by putting annotations in your code need reflection to find and handle them at runtime.

Problem

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 does the `class` keyword signify in `MainActivity.class.getSimpleName();` A full picture of how this code could look and be used ``` public class MainActivity extends AppCompatActivity { // What does "class" signify in the following // MainActivity.class.getSimpleName(); private static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i(TAG, "onCreate()"); } } ```

Original source

Related problems