简体   繁体   中英

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");
    }


}

It's correct. The function's documentation says the following:

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

And since you can assign null to a variable of type Object , this returns true.

Without that documentation, you would be correct in my opinion since null means there is no instance, regardless of the type.

This is expected behavior ( https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/reflect/TypeUtils.html#isInstance(java.lang.Object,%20java.lang.reflect.Type) .

The method just checks if null can be assigned to an Object , it will return true i guess.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM