views:

169

answers:

3

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)

+7  A: 

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.

Thilo
What do you mean by a "Class constant"? When you assign "Class n = Number.class;" what would be the value of n?
Mocha
n gets assigned an instance of Class, the object with describes the Number "class" (which is actually an interface).
Thilo
+3  A: 

The MyClass doesn't have a static getClass method, in other words, you cannot call MyClass.getClass(), instead you need to call (new MyClass()).getClass() for it to work.

getClass() will return a MyClass.class object. So in other words, MyClass.class is the resulting object while getClass() is a method. The getClass() method is useful in cases where you do not know the actual class of the object, for example:


public void someMethod(Object o) {
   if(o.getClass().equals(Set.class)) {
      // The object is a set
   } else if(o.getClass().equals(List.class)) {
     // The object is a List
   }
}

Note that the above code example isn't the best possible, I'm just trying to show how it could be used. The same functionality could be achieved with if(o instanceof Set) { ...}

Kim L
+1  A: 

.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
medopal
".class on the other hand always return the class constant of the "Type" -> What does that mean?
Mocha
@Mocha `Long` is a type, `new Long(2)` is new object of that type
MBO