Java class keyword

╄→гoц情女王★ 提交于 2019-12-23 09:26:48

问题


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,


回答1:


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)



回答2:


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




回答3:


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




回答4:


When you do JFrame.class you are getting a Class<JFrame> instance, so you can call the getName method.

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



来源:https://stackoverflow.com/questions/16288156/java-class-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!