开发者

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 he开发者_运维知识库lpful 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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜