Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: Class.isInstance vs Class.isAssignableFrom

Tags:

java

Let clazz be some Class and obj be some Object.

Is

clazz.isAssignableFrom(obj.getClass()) 

always the same as

clazz.isInstance(obj) 

?

If not, what are the differences?

like image 257
Albert Avatar asked Oct 16 '10 14:10

Albert


People also ask

What is isAssignableFrom in Java?

The isAssignableFrom() method of java. lang. Class class is used to check if the specified class's object is compatible to be assigned to the instance of this Class. It will be compatible if both the classes are the same, or the specified class is a superclass or superinterface.

What is the difference between class isInstance and 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.

How do you check if a class is an instance of another class?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

What is isAssignableFrom Kotlin?

isAssignableFrom() determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.


1 Answers

clazz.isAssignableFrom(Foo.class) will be true whenever the class represented by the clazz object is a superclass or superinterface of Foo.

clazz.isInstance(obj) will be true whenever the object obj is an instance of the class clazz.

That is:

clazz.isAssignableFrom(obj.getClass()) == clazz.isInstance(obj) 

is always true so long as clazz and obj are nonnull.

like image 88
uckelman Avatar answered Sep 18 '22 14:09

uckelman