简体   繁体   English

Java中的MyClass.class代表什么?

[英]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.classClass类型的文字值(与"..."相同,是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中找到。

.class returns object of class Class and yes it applicable to all classes. .class返回类Class的对象,是的,它适用于所有类。 Is Java core class. 是Java核心类。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM