Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between calling MyClass.class and MyClass.getClass() [duplicate]

MyClass.class and MyClass.getClass() both seem to return a java.lang.Class. Is there a subtle distinction or can they be used interchangeably? Also, is MyClass.class a public property of the superclass Class class? (I know this exists but can't seem to find any mention of it in the javadocs)

like image 281
Mocha Avatar asked Mar 18 '10 06:03

Mocha


People also ask

What does getClass method do?

The Java Object getClass() method returns the class name of the object.

What is MyClass in Java?

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 ).


2 Answers

One is an instance method, so it returns the class of the particular object, the other is a Class constant (i.e. known at compile-time).

 Class n = Number.class;
 Number o = 1;
 o.getClass() // returns Integer.class
 o = BigDecimal.ZERO;
 o.getClass();  // returns BigDecimal.class

Both cases return instances of the Class object, which describes a particular Java class. For the same class, they return the same instance (there is only one Class object for every class).

A third way to get to the Class objects would be

Class n = Class.forName("java.lang.Number");

Keep in mind that interfaces also have Class objects (such as Number above).

Also, is MyClass.class a public property of the superclass Class class?

It is a language keyword.

like image 58
Thilo Avatar answered Sep 28 '22 23:09

Thilo


.getClass() returns the runtime class of the object, so it can be modified when you change the class of the variable

.class on the other hand always return the class constant of the "Type"

NOTE
If the runtime class happens to be the same as the TYPE class, both will be equal. Example:

Long x = new Long(2);
Class c1 = Long.class;
Class c2 = x.getClass();

//c1==c2
like image 32
medopal Avatar answered Sep 28 '22 23:09

medopal