在java中将原始类型数组转换为对象数组 [英] Cast primitive type array into object array in java

查看:80
本文介绍了在java中将原始类型数组转换为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能在 java 中做到这一点?

Why I cannot do this in java?

Object[] o = (Object[])(new int[]{0,1,2,3.14,4});

我有一个方法可以接收一个对象,然后将它表示为一个字符串,但这取决于他的类型(原始、原始包装器、数组等...).当我创建单元测试时,我将数组作为 Object 传递,这很好,但是当我将该对象强制转换为 Object[] 时,我得到 <强>ClassCastException.这仅发生在原始类型数组中.有什么办法可以避免这种行为吗?如果没有,有人可以解释一下 Java 虚拟机上这种行为的原因是什么.

I have a method that receives an object and then represents it as a string, but depending on his type (primitive, primitive wrapper, array, etc...). When I was creating a Unit test, I was passing an array as Object which is Ok, but when I perform cast of that object into Object[] I'm getting ClassCastException. This is only happening with primitive type arrays. Is there any way to avoid this behavior? If not, could someone explain what is the reason of this behavior on Java Virtual Machine.

非常感谢任何帮助.

推荐答案

原始类型不能以这种方式转换.在您的情况下,有一个 double 值数组,原因为 3.14.这将起作用:

Primitive type cannot be transformed in this way. In your case, there is an array of double values, cause of 3.14. This will work:

    List<Object> objectList = new ArrayList<Object>();
    objectList.addAll(Arrays.asList(0,1,2,3.14,4));

即使这样也有效:

List<Object> objectList = new ArrayList<Object>();
objectList.addAll(Arrays.asList(0,"sfsd",2,3.14,new Regexp("Test")));
for(Object object:objectList)
{
    System.out.println(object);
}

更新好的,正如前面所说,没有直接的方法可以将原始数组转换为 Object[].如果你想要一个方法来转换字符串中的任何数组,我可以这样建议

UPDATE Ok, there as there was said, there is not direct way to cast a primitive array to an Object[]. If you want a method that transforms any array in String, I can suggest this way

public class CastArray {

    public static void main(String[] args) {
        CastArray test = new CastArray();
        test.TestObj(new int[]{1, 2, 4});
        test.TestObj(new char[]{'c', 'a', 'a'});
        test.TestObj(new String[]{"fdsa", "fdafds"});
    }

    public void TestObj(Object obj) {
        if (!(obj instanceof Object[])) {
            if (obj instanceof int[]) {
                for (int i : (int[]) obj) {
                    System.out.print(i + " ");
                }
                System.out.println("");
            }
            if (obj instanceof char[]) {
                for (char c : (char[]) obj) {
                    System.out.print(c + " ");
                }
                System.out.println("");
            }
            //and so on, for every primitive type.
        } else {
            System.out.println(Arrays.asList((Object[]) obj));
        }
    }
}

是的,为每个原始类型编写循环很烦人,但没有其他方法,恕我直言.

Yes, it's annoying to write a loop for every primitive type, but there is no other way, IMHO.

这篇关于在java中将原始类型数组转换为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆