Java 数组反射:isArray vs. instanceof [英] Java array reflection: isArray vs. instanceof
问题描述
使用之间是否存在偏好或行为差异:
if(obj.getClass().isArray()) {}
和
if(obj instanceof Object[]) {}
?
在大多数情况下,您应该使用 instanceof
运算符来测试对象是否为数组.
通常,您在向下转换为编译时已知的特定类型之前测试对象的类型.例如,也许您编写了一些可以使用 Integer[]
或 int[]
的代码.你想用 instanceof
保护你的演员表:
if (obj instanceof Integer[]) {Integer[] 数组 = (Integer[]) obj;/* 使用装箱数组 */} else if (obj instanceof int[]) {int[] 数组 = (int[]) obj;/* 使用原始数组 */} 别的 ...
在 JVM 级别,instanceof
运算符转换为特定的 "instanceof" 字节码,在大多数 JVM 实现中进行了优化.
在极少数情况下,您可能会使用反射来遍历未知类型的对象图.在这种情况下,isArray()
方法会很有帮助,因为您在编译时不知道组件类型;例如,您可能正在实现某种序列化机制,并且能够将数组的每个组件传递给相同的序列化方法,而不管类型如何.
有两种特殊情况:空引用和对原始数组的引用.
空引用将导致 instanceof
结果 false
,而 isArray
抛出 NullPointerException
.>
应用于原始数组,除非右侧操作数上的组件类型与组件类型完全匹配,否则 instanceof
会产生 false
.相反,对于任何组件类型,isArray()
将返回 true
.
Is there a preference or behavior difference between using:
if(obj.getClass().isArray()) {}
and
if(obj instanceof Object[]) {}
?
In most cases, you should use the instanceof
operator to test whether an object is an array.
Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a Integer[]
or an int[]
. You'd want to guard your casts with instanceof
:
if (obj instanceof Integer[]) {
Integer[] array = (Integer[]) obj;
/* Use the boxed array */
} else if (obj instanceof int[]) {
int[] array = (int[]) obj;
/* Use the primitive array */
} else ...
At the JVM level, the instanceof
operator translates to a specific "instanceof" byte code, which is optimized in most JVM implementations.
In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the isArray()
method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.
There are two special cases: null references and references to primitive arrays.
A null reference will cause instanceof
to result false
, while the isArray
throws a NullPointerException
.
Applied to a primitive array, the instanceof
yields false
unless the component type on the right-hand operand exactly matches the component type. In contrast, isArray()
will return true
for any component type.
这篇关于Java 数组反射:isArray vs. instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!