简体   繁体   中英

What does MyClass.class in Java represent?

I have come across code in the form:

MyClass.class.getName();

Is .class a property?

Is it applicable to ALL classes? (is it inherited from Object class?)

What type of object is returned by .class ?

What other functions like getName() does the .class have?

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.

Thanks in advance.

MyClass.class is a literal value of type Class (the same way as "..." is a literal value of type String ).

It's available for all classes and interfaces, and also for primitive types ( int.class ).

Since Class is generic, type of MyClass.class is Class<MyClass> , so that you can do this:

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 returns object of class Class and yes it applicable to all classes. Is Java core class.

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. You can call java.lang.Object.class , but not obj.class . Instead you should use obj.getClass() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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