Array.newIntance 返回 Object

In general, use the instanceof operator to test whether an object is an array.

At the JVM level, the instanceof operator translates to a specific "instanceof" byte code, which is highly optimized in most JVM implementations.

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.

A null reference will cause instanceof to result false, while the isArray throws a NullPointerException.

Applied to a primitive array, the instanceof results false, but the isArray returns true.

-------------------------------------------------------------------------------------------------------

注:Array 的getX 及 setX 方法中的第一个参数,也是作为Object的 Array:

static Objectget(Object array, int index)
          返回指定数组对象中索引组件的值。
static booleangetBoolean(Object array, int index)
          以 boolean 形式返回指定数组对象中索引组件的值。
static voidset(Object array, int index,Object value)
          将指定数组对象中索引组件的值设置为指定的新值。
static voidsetBoolean(Object array, int index, boolean z)
          将指定数组对象中索引组件的值设置为指定的 boolean 值。

---------------------------------------------------------------------------------------------------

java.lang.reflectClass.Array.newInstance的方法签名

1static Object   newInstance(Class<?> componentType,int length)
2          Creates anew array with the specified component type and length.
3static Object   newInstance(Class<?> componentType,int[] dimensions)
4          Creates anew array with the specified component type and dimensions.

 非基本类型的数组 String[] Integer[]都是Object[]的子类,往上是 Object的子类。
1String[] str = {"2"};
2System.out.println(str instanceofObject[]);
3System.out.println(str instanceofObject);

但是基本类型不是,int[] long[]这些只是Object的子类。

子类的数组是其父类数组的子类是针对对象,基本类型不是对象。

1int[] i={1,2,3};
2int[] newI=(int[])java.lang.reflect.Array.newInstance(i.getClass().getComponentType(),3);
3for(inttmp:newI)
4    System.out.println(tmp);

输出
10
20
30
4 
5Process finished with exit code 0

这个方法最后会调用到 native 方法

1private staticnative Object newArray(Class componentType,int length)
2throws NegativeArraySizeException;

Array.newIntance主要是拿来在泛型集合生成对应数组的时候用到,用native方法,生成一个comonentType的数组,返回object,强转。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值