Java数组反射:IsArray的主场迎战的instanceof [英] Java array reflection: isArray vs. instanceof
问题描述
有没有使用之间的preference或行为差异:
Is there a preference or behavior difference between using:
if(obj.getClass().isArray()) {}
和
if(obj instanceof Object[]) {}
推荐答案
在一般情况下,使用的instanceof
运算符来测试一个对象是否为数组。
In general, use the instanceof
operator to test whether an object is an array.
在JVM层面,的instanceof
运营商转换到一个特定的的instanceof字节code,这是大多数的JVM实现高度优化。
At the JVM level, the instanceof
operator translates to a specific "instanceof" byte code, which is highly optimized in most JVM implementations.
反射方法(的getClass()。IsArray的()
)被编译成两个独立的invokevirtual说明。由JVM对这些所施加的更通用的优化可能不一样快于的instanceof指令所固有的手动调整的优化。
The reflective approach (getClass().isArray()
) is compiled to two separate "invokevirtual" instructions. The more generic optimizations applied by the JVM to these may not be as fast as the hand-tuned optimizations inherent in the "instanceof" instruction.
有两种特殊情况:空引用和参考基本数组
There are two special cases: null references and references to primitive arrays.
一个空引用会导致的instanceof
导致假
,而 IsArray的
抛出一个 NullPointerException异常
。
A null reference will cause instanceof
to result false
, while the isArray
throws a NullPointerException
.
适用于基本数组,在的instanceof
收益率假
,除非右手操作的组件类型完全匹配。相比之下, IsArray的()
将返回真正
任何组件类型。
Applied to a primitive array, the instanceof
yields false
unless the right-hand operand exactly matches the component type. In contrast, isArray()
will return true
for any component type.
这篇关于Java数组反射:IsArray的主场迎战的instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!