What does isInstance mean is the "dynamic equivalent" of an instance?

What does dynamic equivalent mean?

I just wonder why the purpose of this.getClass().isInstance(aClass) instead of this instanceof aClass ? Is there any difference?

Determines whether the specified compatibility object matches the object represented by this class. This method is the dynamic equivalent of a Java instance statement.

+6
source share
2 answers

Yes. Not only the order is wrong, but the object instanceof Clazz must have a class that is known at compile time. clazz.isInstance(object) can take a class that is known at runtime.

There is also a subtle difference in that isInstance will load automatically, but instanceof will not.

eg.

 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 using them.

Note: if you execute object.getClass().getClass() or myClass.getClass() , you just get Class Be careful not to call getClass() when you don't need it.

+11
source

The instanceof operator checks if the object is an instance of a fixed (static) class; that is, a class whose name is known at compile time.

The Class.isInstance method allows you to test a dynamic class; that is, a class that is known only at runtime.


I just wonder why the purpose of this.getClass().isInstance(aClass) instead of this instanceof aClass ? Is there any difference?

The purpose of isInstance is as above.

The main difference between these two expressions:

  • in the first, aClass is a variable whose value is a Class object and

  • in the second, aClass is the name of the class: it CANNOT be a variable.

+4
source

Source: https://habr.com/ru/post/952984/


All Articles