使用之间是否存在偏好或行为差异:
if(obj.getClass().isArray()) {}
和
if(obj instanceof Object[]) {}
?
最佳答案
在大多数情况下,您应该使用 instanceof
运算符来测试对象是否为数组。
通常,您在向下转换为编译时已知的特定类型之前测试对象的类型。例如,也许您编写了一些可以使用 Integer[]
或 int[]
的代码。你想用 instanceof
保护你的 Actor :
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 ...
在 JVM 级别,instanceof
运算符转换为特定的 "instanceof"字节码,在大多数 JVM 实现中进行了优化。
在极少数情况下,您可能会使用反射来遍历未知类型的对象图。在这种情况下,isArray()
方法会很有帮助,因为您在编译时不知道组件类型;例如,您可能正在实现某种序列化机制,并且能够将数组的每个组件传递给相同的序列化方法,而不管类型如何。
有两种特殊情况:空引用和对原始数组的引用。
空引用会导致 instanceof
产生 false
,而 isArray
会抛出 NullPointerException
。
应用于原始数组,instanceof
产生 false
,除非右侧操作数上的组件类型与组件类型完全匹配。相比之下,isArray()
将为任何组件类型返回 true
。
关于Java数组反射: isArray vs. instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/219881/