Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java class keyword

I found a few days ago a code in Java that uses the class keyword in the context, for example:

MyConcreteClass.class.AMethod();

I've tried to do it in a JFrame, for example:

JFrame.class.getName();

And that works but... I can't figure out/find on the internet what this keyword means in that context. I've only used it to declare classes.

Can anyone explain me what class means in this context?

Thanks,

like image 543
vicaba Avatar asked Apr 29 '13 21:04

vicaba


3 Answers

In this context class is not a keyword, it's a special attribute (a "class literal") of a class denoting its corresponding instance of Class. For example, to obtain the Class object of String, we do this: String.class. The value returned is the instance of Class that represents String's class (notice the use of upper and lowercase).

Here .class is used on the actual class, to obtain the same result using one of its instances we use the getclass() method. Continuing with our example, this snippet returns the same instance of Class corresponding to a String: "".getClass().

To round the idea - this snippet will always return true, for any class with a corresponding instance you want to test:

"".getClass().equals(String.class)
like image 171
Óscar López Avatar answered Nov 15 '22 06:11

Óscar López


In this context, class is part of a class literal referring to the Class object representing that class.

like image 30
Andy Thomas Avatar answered Nov 15 '22 07:11

Andy Thomas


Using the class keyword in your example will give you an object instance of the Class<JFrame> type.

like image 33
ecbrodie Avatar answered Nov 15 '22 07:11

ecbrodie