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

有帮助吗?

解决方案

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 of this 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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top