Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are instances of Class class guaranteed to be singletons per classloader?

Tags:

java

So is it valid to check for class equality in this way:

if (object.getClass() == anotherObject.getClass()) {

}

Probably the answer is yes because Class class does not override equals() so it looks like Object.equals() applies for Class equality. But, I would be interested if this is documented somewhere else. Thanks.

like image 517
Nazaret K. Avatar asked Apr 28 '16 10:04

Nazaret K.


People also ask

What is a singleton class?

In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time.

Why do we need a classloader in Java?

If a loaded class depends on another class, that class is loaded as well. When we request to load a class, it delegates the class to its parent. In this way, uniqueness is maintained in the runtime environment. It is essential to execute a Java program. Java ClassLoader is based on three principles: Delegation, Visibility, and Uniqueness.

What is the difference between application classloader and extension classloader?

Now request transfer to Extension ClassLoader which searches for the directory jre/lib/ext and tries to locate this class there. If the class is found there, Extension ClassLoader loads that class. Application ClassLoader never loads that class.

What is the difference between primordial classloader and extensions classloader?

It is also called Primordial ClassLoader. It loads class files from jre/lib/rt.jar. For example, java.lang package class. Extensions Class Loader: It delegates class loading request to its parent. If the loading of a class is unsuccessful, it loads classes from jre/lib/ext directory or any other directory as java.ext.dirs.


1 Answers

Refer to JLS Section 12.2:

Well-behaved class loaders maintain these properties:

  • Given the same name, a good class loader should always return the same class object.
  • ...

A malicious class loader could violate these properties. However, it could not undermine the security of the type system, because the Java Virtual Machine guards against this.

So, provided your instances are of classes loaded by the same class loader, you can test using identity.

like image 195
Andy Turner Avatar answered Sep 21 '22 14:09

Andy Turner