Search code examples
javaapacheapache-commons

TypeUtils says "null" is instance of "Object.class"?


Regarding following code org.apache.commons.lang3.reflect.TypeUtils says null is a type of Object.class. Isn't this incorrect ?

public static void main(String args[]) {

    Boolean bool = null;

    if (TypeUtils.isInstance(bool, Object.class)) {
        System.out.println("bool isInstance Object-true");
    } else {
        System.out.println("bool isInstance Object-false");
    }


}

Solution

  • I agree with you. The isInstance() method is misleading. It should be rather isAssignable() since the documentation indicates it :

    Checks if the given value can be assigned to the target type following the Java generics rules.

    And null is not a instance of Object class since null is not an instance.

    But your result is accurate according to the documentation since null can be assigned to any object type. And when you look the implementation, you can see that the code calls a isAssignable() method :

    public static boolean isInstance(final Object value, final Type type) {
        if (type == null) {
            return false;
        }
    
        return value == null ? !(type instanceof Class<?>) || !((Class<?>) type).isPrimitive()
                : isAssignable(value.getClass(), type, null);
    }