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)
The Java Object getClass() method returns the class name of the object.
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 ).
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.
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With