Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When creating an Android intent and specifying target activity, what is this ".class" syntax?

This is, perhaps, a stupid question, but I've found nothing on it elsewhere. I'm going through the basics of Android, and when I try to create an intent specifically to run another activity of my choosing, the tutorial tells me to construct it this way:

Intent intent = new Intent(this, DisplayMessageActivity.class);

Where "DisplayMessageActivity" is the class for the activity I'm running. What I don't get is, what's the ".class" part? That parameter, as I understand it, is supposed to be a Class object. Is "class" a field of my Activity subclass? Or when I say "DisplayMessageActivity.class", am I referring to an actual .class file (that seems a little weird)?

Any help is appreciated!

like image 758
hunt Avatar asked Oct 13 '12 04:10

hunt


2 Answers

While the .class appears to be a normal field access, it is actually a special language construct, that is explained very well in the Retrieving Class Objects Java tutorial.

It says, quote:

If the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

And they give the example:

boolean b;
Class c = b.getClass();   // compile-time error

Class c = boolean.class;  // correct


In my day to day usage of Java, this isn't a hugely used construct, and many are unaware of it. Generally it's used with generics and the like when specificing classes in general rather than instances of them.

I hope this helps. :)

like image 57
Miguel Avatar answered Sep 19 '22 15:09

Miguel


What I don't get is, what's the ".class" part? That parameter, as I understand it, is supposed to be a Class object.

That is correct.

The SomeClass.class is actually Java syntax that means "give me the Class object that corresponds to the SomeClass type". And note that you can use it on any type ... not just class names.

Is "class" a field of my Activity subclass?

No. It is not a field. You could think of it as analogous to a static field, but actually it is no such thing. (Just like someArray.length is not really a field of the array object.)

Or when I say "DisplayMessageActivity.class", am I referring to an actual .class file

It is referring to a Class object ... not a ".class" file.

like image 39
Stephen C Avatar answered Sep 16 '22 15:09

Stephen C