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.
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time.
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.
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.
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.
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.
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