Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I really do mean identity-equality here.

For example, will the following always print true?

System.out.println("foo".getClass() == "fum".getClass());
like image 785
Mackenzie Avatar asked Sep 17 '10 20:09

Mackenzie


People also ask

What does getClass () do in Java?

getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.

What is object getClass?

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

What does getClass () getName () Do Java?

The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object.

Can we override getClass method?

You cannot override getClass .


3 Answers

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.

like image 102
Péter Török Avatar answered Oct 09 '22 20:10

Péter Török


For two instances of class X,

x1.getClass() == x2.getClass()

only if

x1.getClass().getClassLoader() == x2.getClass().getClassLoader()

Note: Class.getClassLoader() may return null which implies the bootstrap ClassLoader.

like image 16
McDowell Avatar answered Oct 09 '22 20:10

McDowell


Yes.

The returned Class object is the object that is locked by static synchronized methods of the represented class.

If it was possible to return multiple instances, then

public static synchronized void doSomething() {..}

would not be thread-safe.

like image 8
Bozho Avatar answered Oct 09 '22 18:10

Bozho