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!
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. :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With