[英]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
. 关于以下代码,
org.apache.commons.lang3.reflect.TypeUtils
说null
是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.
检查是否可以按照Java泛型规则将给定值分配给目标类型。
And since you can assign null
to a variable of type Object
, this returns true. 并且由于可以将
null
分配给Object
类型的变量,因此返回true。
Without that documentation, you would be correct in my opinion since null
means there is no instance, regardless of the type. 没有该文档,我认为您是正确的,因为
null
表示没有实例,无论类型如何。
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) . 这是预期的行为( https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/reflect/TypeUtils.html#isInstance(java.lang.Object,%20java.lang。 Reflection.Type) 。
The method just checks if null can be assigned to an Object , it will return true i guess. 该方法只是检查是否可以将null分配给Object,我猜它将返回true。
I agree with you. 我同意你的看法。 The
isInstance()
method is misleading. isInstance()
方法具有误导性。 It should be rather isAssignable()
since the documentation indicates it : 它应该是
isAssignable()
因为文档指出了它:
Checks if the given value can be assigned to the target type following the Java generics rules.
检查是否可以按照Java泛型规则将给定值分配给目标类型。
And null is not a instance of Object class since null is not an instance. 而且null不是Object类的实例,因为null不是实例。
But your result is accurate according to the documentation since null
can be assigned to any object type. 但是根据文档,您的结果是准确的,因为可以将
null
分配给任何对象类型。 And when you look the implementation, you can see that the code calls a isAssignable()
method : 当您查看实现时,可以看到代码调用了
isAssignable()
方法:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.