Does Java Guarantee That Object.Getclass() == Object.Getclass()

Does Java guarantee that Object.getClass() == Object.getClass()?

Yes, class tokens are unique (for any given classloader, that is).

I.e. you will always get a reference to the same physical object within the same classloader realm. However, a different classloader will load a different class token, in conjunction with the fact that the same class definition is deemed different when loaded by two distinct classloaders.

See this earlier answer of mine for a demonstration of this.

Does Java guarantee that the Class object returned by getClass() will always be the same instance?

Yes, the class object will be the same so long as the two classes were loaded by the same classloader.

But if they weren't, the two classes have to be regarded as different, even though they may share the same name and code. (This is something that can easily be run into when using multiple classloaders, so it's worth remembering.)

Does calling Object.getClass() itself use Reflection?

Checking the definitive source for Java's definition of reflection, the Java Language Specification, section 1.4. Relationship to Predefined Classes and Interfaces, simply says:

Consequently, this specification does not describe reflection in any detail. Many linguistic constructs have analogs in the Core Reflection API (java.lang.reflect) and the Language Model API (javax.lang.model), but these are generally not discussed here.

The Java Virtual Machine Specification, section 2.12. Class Libraries, says:

Classes that might require special support from the Java Virtual Machine include those that support:

  • Reflection, such as the classes in the package java.lang.reflect and the class Class.

So, you use reflection if you:

  • Use the Class type, e.g. obtained using Foo.class, obj.getClass() or Class.forName()
  • Use any type in package java.lang.reflect
  • Use any type in package javax.lang.model

Note that the Class object returned by getClass() doesn't actually exist until you call it the first time. Classes are internally stored in a difference way, and operations like instanceof functions without having to instantiate the much heavier Class object, for performance reasons.

When does var.getClass() return Object?

Object.getClass() returns

The Class object that represents the runtime class of this object.

(Object API docs)

That will be java.lang.Object.class if and only if the object's class is exactly java.lang.Object (not a subclass). This method is final, so you can rely on every object providing that implementation.

You may, however, also be interested in Class.isAssignableFrom() if you are looking for a way to determine reflectively whether one class is a superclass of another.

Could someone explain me the .getClass() method in java

You first need to know how == and != compare the two operands. The reason why == and != cannot be used to compare reference types is that they actually compare the memory addresses of the two reference type variables.

So if I have two strings:

String x = "Hello";
String y = x;

Since x and y share the same memory address after the second line is executed, x == y evaluates to true.

The same goes for the getClass() method. The getClass() method returns the class of the object as a Class<T> object. The question is, why this evaluates to true:

x.getClass() == y.getClass()

The answer is simple. Because x and y are both of type String. So calling getClass will return the same instance. This means the two returned the objects share the same memory address.

"But when I compare strings with the same characters with the == operator, it evaluates to false!" you shouted.

This is because the strings are located at different memory addresses. But the classes that getClass will return is always at the same memory address if the class that they represent is the same. This is due to the way ClassLoader works. But I'm not an expert that.

You just need to know that the objects returned by getClass is at the same memory address if the classes they represent are the same.

Any reason to prefer getClass() over instanceof when generating .equals()?

If you use instanceof, making your equals implementation final will preserve the symmetry contract of the method: x.equals(y) == y.equals(x). If final seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the Object class.


What I'm trying to get at here is that if you believe getClass() is the only reliable way to preserve symmetry, you are probably using equals() the wrong way.

Sure, it's easy to use getClass() to preserve the symmetry required of equals(), but only because x.equals(y) and y.equals(x) are always false. Liskov substitutability would encourage you to find a symmetry-preserving implementation that can yield true when it makes sense. If a subclass has a radically different notion of equality, is it really a subclass?

How to determine an object's class?

if (obj instanceof C) {
//your code
}

Are Java Class objects unique / singletons?

You can have one singleton and/or class per class loader.

a.equals(b) is required to be true if a == b (except if a is null)

instanceof Vs getClass( )

The reason that the performance of instanceof and getClass() == ... is different is that they are doing different things.

  • instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.

  • getClass() == ... tests whether the types are identical.

So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.

Is using the instanceOf operator bad practice ?

Not necessarily. Overuse of either instanceOf or getClass() may be "design smell". If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking. In most situations, the preferred approach is to use polymorphism.

However, there are cases where these are NOT "design smell". For example, in equals(Object) you need to test the actual type of the argument, and return false if it doesn't match. This is best done using getClass().


Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice". I recommend that everyone read No Best Practices if they haven't already done so.



Related Topics



Leave a reply



Submit