Java类关键字
我在几天前发现一个在上下文中使用类关键字的Java代码,例如:
I found a few days ago a code in Java that uses the class keyword in the context, for example:
MyConcreteClass.class.AMethod();
我试图在JFrame中做,例如:
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,
在此上下文中 class
不是关键字,它是类的特殊属性(类文字),表示其对应的实例 Class
。例如,要获取 String
的 Class
对象,我们这样做: String.class
。返回的值是 Class
的实例,代表 String
的类(注意使用大小写)。
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).
这里 .class
用于实际的类,使用它的一个实例获得相同的结果方法 getclass()
。继续我们的示例,此代码段返回与 String
对应的 Class
的相同实例: .getClass()
。
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()
.
为了使想法更圆滑,此代码段总是返回 true
,对于任何具有相应实例的类你想测试:
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)