Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does MyClass.class in Java represent?

Tags:

java

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.

like image 968
Shailesh Tainwala Avatar asked Dec 28 '22 00:12

Shailesh Tainwala


1 Answers

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.

like image 143
axtavt Avatar answered Dec 30 '22 14:12

axtavt