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

java, reflection

Solution

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.

Problem

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

Original source

Related problems