Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between instanceof and Class.isAssignableFrom(...)?

Which of the following is better?

a instanceof B 

or

B.class.isAssignableFrom(a.getClass()) 

The only difference that I know of is, when 'a' is null, the first returns false, while the second throws an exception. Other than that, do they always give the same result?

like image 395
Megamug Avatar asked Jan 30 '09 19:01

Megamug


People also ask

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.

What is isAssignableFrom?

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 an Instanceof?

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.

What is the difference between using the getClass method and using the Instanceof operator?

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.


2 Answers

instanceof can only be used with reference types, not primitive types. isAssignableFrom() can be used with any class objects:

a instanceof int  // syntax error 3 instanceof Foo  // syntax error int.class.isAssignableFrom(int.class)  // true 

See http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class).

like image 23
Adam Rosenfield Avatar answered Oct 14 '22 06:10

Adam Rosenfield


When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.

like image 196
Marc Novakowski Avatar answered Oct 14 '22 05:10

Marc Novakowski