Java class keyword

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

MyConcreteClass.class.AMethod(); 

I tried to do this in a JFrame, for example:

 JFrame.class.getName(); 

And it works, but ... I cannot understand / find on the Internet what this keyword means in this context. I used it only to declare classes.

Can someone explain to me what class means in this context?

Thanks,

+6
source share
4 answers

In this context, class not a keyword, it is a special attribute ("class literal") of the class, denoting its corresponding instance of the class . For example, to get the class object of a String object, we do the following: String.class . The return value is an instance of the class that represents the String class (note the use of upper and lower case).

Here .class used for the actual class, to get the same result using one of its instances, we use the getclass() method. Continuing our example, this fragment returns the same class instance that matches String : "".getClass() .

To get around the idea - this snippet will always return true for any class with the corresponding instance that you want to check:

 "".getClass().equals(String.class) 
+6
source

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

+2
source

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

+1
source

When you do JFrame.class, you get an instance of Class<JFrame> , so you can call the getName method.

A class literal allows you to access information about the class in question.

+1
source

Source: https://habr.com/ru/post/943913/


All Articles