关于Object数组强转成Integer数组的问题:Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; |
您所在的位置:网站首页 › object转为int › 关于Object数组强转成Integer数组的问题:Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; |
一、当把Object数组,强转的具体的Integer数组时,会报错。 代码如下: //数组强转报错演示 Object[] numbers = {1,2,3}; Integer[] ints = (Integer[])numbers;报错: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;原因: 根本原因还是类型的继承关系问题,Integer[]并不是Object[]的子类。虽然,Integer继承自Object,但Integer[]的直接父类是Object。即所有数组类型的直接父类都是Object,可以通过反射来验证。数组类型是写在jvm里得,就像8种基本类型,我们无法在java的标准库中找到这个类。 //数组的直接父类演示@Test public void testArrayClass() { Integer[] i = {1,2,3}; Object[] o = {1,2,3}; System.out.println(o.getClass().getSuperclass().getName()); System.out.println(i.getClass().getSuperclass().getName()); }输出结果: java.lang.Object java.lang.Object
解决方案,可以对数组每个成员分别转化: @Test public void testArrayChange() { Object[] numbers = {1,2,3}; Integer[] ints = new Integer[numbers.length]; for(int i = 0;i |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |