Java: Class.Isinstance VS Class.Isassignablefrom

java: Class.isInstance vs Class.isAssignableFrom

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.

Class#isInstance vs Class#isAssignableFrom

isAssignableFrom also tests whether the type can be converted via an identity conversion or via a widening reference conversion.

    Class<?> cInt = Integer.TYPE;

Long l = new Long(123);

System.out.println(cInt.isInstance(l)); // false
System.out.println(cInt.isAssignableFrom(cInt)); // true

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

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.

Compare object with class stored in field

Instead of this

if(part instanceof c) return true;

Try this

if(c.isAssignableFrom(part.getClass())) return true;

This is different than Class.isInstance(Object), because isAssignableFrom also returns true when part is the same type as or a sub-class of c.

So if you need to know if this is the exact same type use isInstance, if it could also be a sub-class, then use isAssignableFrom.

confusion about Class.isInstance

To re-quote the javadoc

Determines if the specified Object is assignment-compatible *
with the object represented by this Class.

In the expression

java.lang.Integer.class.isInstance(java.lang.Number.class);

you are checking if the object returned by the expression java.lang.Number.class is an instance of Integer. It is not, it is an instance of java.lang.Class.

It should be used like

java.lang.Integer.class.isInstance(new Integer(1)); // if you want it to return true

You can pass it anything you want, but it will only return true if the argument used is an Integer or one of its sub types (but it is final so there aren't any).

Integer is a sub type of Number.

Any Integer instance can be used where a Number object is required.



Related Topics



Leave a reply



Submit