Instanceof and Class.isAssignableFrom(…)What's the difference?

Asked 2 years ago, Updated 2 years ago, 142 views

a instance of B Me

B.class.isAssignableFrom(a.getClass()) The difference I know in is that if a is null, instanceof returns false, and isAssignableFrom drops exception.

Other than that, are they all the same?

java instanceof reflection

2022-09-22 16:43

1 Answers

Instanceof is used when you want to know class B when compiling. IsAssignableFrom() is used to dynamically confirm at runtime.

To check when an object inherits or implements a particular type (class and interface)

if(obj instanceof $TargetClass.class) {
}

You can check it as above.

But how do I check if a particular class has implemented or inherited another interface? I think you can look for all the upper classes (until you become java.lang.Object) and check the interfaces that you implemented, but I don't think it's sophisticated.

The method isAssignableFrom solves the above problem easily.

What I wanted was to check if the class I received from the user was a class that implemented the java.util.Collection interface (implementations).

Class clazz = Class.forName(className);
boolean isCollection = java.util.Collection.class.isAssignableFrom(clazz);

When used as above, it is interpreted as follows. Java.util.Collection can be identified as clazz. In other words, the clazz class is a class that implements the java.util.Collection interface.

Set the className = "java.util.ArrayList" and test it to help you understand.


2022-09-22 16:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.