I am beginner in programming and i just started working with greenfoot (software for creating games using Java). When i was writing code i had to use construction builded in greenfoot which was using parameter described as: java.lang.class where i had to type ClassName.class . I was trying to go through documentation and a lot of other sources to figure out how it works and what is this, but to be honest i couldnt understand anything. Is there is someone who can tell me in simply words what does it mean and how construction like ClassName.class works? That is the first time i see dot notation used like this, before I have seen only dot notation when i tried to refer to for example other class method like: OtherClass.method() . So is it just builded in instance variable of every class or something like this? Thanks in advance
Asked
Active
Viewed 56 times
-5
-
It sounds like you need to pick up a Beginning Java book that describes the Java basics. – Mike Sep 06 '18 at 14:36
-
Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) *"When i was writing code i had to use construction builded in greenfoot which was using parameter described as: java.lang.class where i had to type ClassName.class"* It's always better to **show** than to **tell**. Show the code you're confused by, and point out the part that confuses you. – T.J. Crowder Sep 06 '18 at 14:36
-
@Mike I am actually reading Beginning Java book connected with greenfoot while writing my own code, but it wasn't any explaination about it, just "you don't have to know this at this level" – schemaboi Sep 06 '18 at 14:47
-
@schemaboi - Perhaps you should take the author at their word on the "you don't have to know this at this level" part -- presumably they get to it later, when they've laid enough foundation. – T.J. Crowder Sep 06 '18 at 15:32
1 Answers
1
It's called a class literal. ClassName.class
provides access to the instance of Class
that represents the given class. So for instance, String.class
refers to the Class
instance for the String
class. Using that object, you can do do various things (like find out what its members are at runtime via reflection). (FWIW, objects provide also access to the Class
instance for their class via their getClass
method.)

T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875
-
Thank you, your answer explained me this a little bit. But to be more specific: how compilator interpret ".class" in for example "String.class"? As an instance variable of instance String from class "Class"? Because i dont really understand how dot notation works here – schemaboi Sep 06 '18 at 15:26
-
@schemaboi - No, it's not an instance variable. This is top-level syntax, even though it looks like a property access operation. It isn't (because the class name doesn't refer to an object). See the first link in the answer. – T.J. Crowder Sep 06 '18 at 15:32