[英]What does MyClass.class in Java represent?
I have come across code in the form: 我遇到过以下形式的代码:
MyClass.class.getName();
Is .class a property? .class是属性吗?
Is it applicable to ALL classes? 它适用于所有课程吗? (is it inherited from Object class?)
(它是从Object类继承的吗?)
What type of object is returned by .class ? .class返回什么类型的对象?
What other functions like getName() does the .class have? .class有哪些像getName()这样的函数?
I realize that this is a very basic question, but I wasn't able to locate comprehensive information in the Javadocs, and it would be really helpful if some practical application of .class could be given. 我意识到这是一个非常基本的问题,但是我无法在Javadocs中找到全面的信息,如果可以给出.class的一些实际应用,那将非常有用。
Thanks in advance. 提前致谢。
MyClass.class
is a literal value of type Class
(the same way as "..."
is a literal value of type String
). MyClass.class
是Class
类型的文字值(与"..."
相同,是String
类型的文字值)。
It's available for all classes and interfaces, and also for primitive types ( int.class
). 它适用于所有类和接口,也适用于基本类型(
int.class
)。
Since Class
is generic, type of MyClass.class
is Class<MyClass>
, so that you can do this: 由于
Class
是通用的, MyClass.class
类型是Class<MyClass>
,因此您可以这样做:
Class<MyClass> c = MyClass.class;
MyClass o = c.newInstance(); // No cast needed, since newInstance() on Class<T> returns T
Methods of Class
can be found in its javadoc . Class
方法可以在它的javadoc中找到。
No, it's not a property. 不,这不是财产。 "class" is a special keyword that you can use to get Class object of the class by its name.
“class”是一个特殊的关键字,您可以使用它来获取类名称的Class对象。 You can call
java.lang.Object.class
, but not obj.class
. 您可以调用
java.lang.Object.class
,但不能调用obj.class
。 Instead you should use obj.getClass()
. 相反,你应该使用
obj.getClass()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.