What does it mean 'dynamic equivalent'?
I just wonder what is the purpose of having this.getClass().isInstance(aClass)
instead of this instanceof aClass
? Is there a difference?
Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator
The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator.
instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.
Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
Yes. Not only is the order not the same, but object instanceof Clazz
must have a class which is known at compile time. clazz.isInstance(object)
can take a class which is known at runtime.
There is also subtle difference in that isInstance will auto-box, but instanceof will not.
e.g.
10 instanceof Integer // does not compile
Integer.class.isInstance(10) // returns true
Integer i = 10;
if (i instanceof String) // does NOT compile
if (String.class.isInstance(i)) // is false
To see the difference I suggest you try to use them.
Note: if you do object.getClass().getClass()
or myClass.getClass()
you will just get a Class
Be careful not to call getClass()
when you don't need to.
The instanceof
operator tests to see if an object is an instance of a fixed (static) class; i.e. a class whose name is known at compile time.
The Class.isInstance
method allows you to test against a dynamic class; i.e. a class that is only known at runtime.
I just wonder what is the purpose of having
this.getClass().isInstance(aClass)
instead ofthis instanceof aClass
? Is there a difference?
The purpose of isInstance
is as above.
The primary difference between those two expressions is:
in the first one, aClass
is a variable whose value is a Class
object, and
in the second one, aClass
is the name of a class: it CANNOT be a variable.
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