Java 将对象转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16427319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:53:16  来源:igfitidea点击:

Cast Object to Array

javaarrays

提问by Ryan Epp

So I have an Object which MIGHT be an array. It can also be primitive, or a string. If it is an array, it can be an array of literally anything.

所以我有一个对象,它可能是一个数组。它也可以是原始的或字符串。如果它是一个数组,那么它可以是任何字面上的数组。

I have no problem figuring out if it is an array but I can't seem to cast it into anything that I can iterate through to get the values out of.

我可以确定它是否是一个数组,但我似乎无法将其转换为任何可以迭代以获取值的内容。

// o is an object and clazz is the class of the o
if (clazz == Array.class) {
            Class ofArray = o.getClass().getComponentType();
            String arrayType = ofArray.getName(); // 'Double' for my test case
            //ERROR: [D cannot be cast to [Ljava.lang.Object 
            Object[] objects = (Object[]) o; 
    }

My background is in ruby and php (where it would just work) and the static typing is messing with my head. Any ideas?

我的背景是 ruby​​ 和 php(它可以正常工作),静态类型弄乱了我的头脑。有任何想法吗?

EDIT:

编辑:

This throws the error

这会引发错误

[D cannot be cast to [Ljava.lang.Object.

What am I missing?

我错过了什么?

if (o.getClass().isArray()) {
    Object[] objects = (Object[]) o;  
}

采纳答案by Vegard

If you do not want to make the switch for all primitive types you could do like this:

如果您不想为所有原始类型进行切换,您可以这样做:

if (ofArray.isPrimitive()) {
    int length = Array.getLength(o);
    for (int i = 0; i < length; i++) {
        Object obj = Array.get(o, i);
        System.out.println(obj);
    }
}
else {
    Object[] objects = (Object[]) o;
    for (Object obj : objects) {
        System.out.println(obj);
    }
}

Edit: If you don't want to loop in two different places in your code use this method to convert the primitive arrays to an object array:

编辑:如果您不想在代码中的两个不同位置循环,请使用此方法将原始数组转换为对象数组:

static Object[] convertToObjectArray(Object array) {
    Class ofArray = array.getClass().getComponentType();
    if (ofArray.isPrimitive()) {
        List ar = new ArrayList();
        int length = Array.getLength(array);
        for (int i = 0; i < length; i++) {
            ar.add(Array.get(array, i));
        }
        return ar.toArray();
    }
    else {
        return (Object[]) array;
    }
}

回答by óscar López

This will work for arrays with elements that are sublcasses of Object:

这将适用于具有以下子类的元素的数组Object

if (clazz.isArray()) {
    Object[] objects = (Object[]) o;
    for (Object obj : objects)
        System.out.println(obj);
}   

If you need to cast the array to an specific array type you could (ab)use instanceofbut for, say, just printing the contents as strings, an Object[]suffices.

如果您需要将数组转换为特定的数组类型,您可以 (ab) 使用,instanceof但例如,只需将内容打印为字符串,Object[]就足够了。

UPDATE

更新

If the array is of primitive types, you have no option but to test for each one and cast to the correct type, Object[]won't work for this case - but there aren't thatmany primitive types in Java, so it won't be a gigantic switch :) . This is what I mean:

如果数组是原始类型,你别无选择,只能测试每一个并转换为正确的类型,Object[]在这种情况下不起作用 - 但Java中没有那么多原始类型,所以它不会成为一个巨大的开关 :) 。这就是我的意思:

if (clazz.isArray()) {
    if (clazz.getComponentType().equals(double.class)) {
        double[] numbers = (double[]) o;
        for (double d : numbers)
            System.out.println(d);
    }
}  

回答by fjf2002

It's not enough to know your Objectis an array - you should also know the underlying type of the array elements. If your array elements are of primitive type, say double, you need to

仅仅知道你Object是一个数组是不够的——你还应该知道数组元素的底层类型。如果您的数组元素是原始类型,例如double,您需要

double[] doubleArray = (double[]) o;  

This won't work:

这行不通:

Object[] objects = (Object[]) o;  

回答by Ravi Thapliyal

You cannot type cast an Array of primitives to an Object[]

您不能将原始数组类型转换为 Object[]

if (clazz == Array.class) {
  Class ofArray = o.getClass().getComponentType();
  // String arrayType = ofArray.getName(); // 'Double' for my test case
  if (ofArray instanceof double.class)
    double[] doubles = (double[]) o;
  for (double d: doubles)
    System.out.println(d);
}

To create an Object[]without instanceofchecks

创建一个Object[]没有instanceof检查的

if (!(o instanceof Object[])) {
  int len = Array.getLength(o);
  Object[] objects = new Object[len];
  for (int i = 0; i < len; i++)
    objects[i] = Array.get (o, i);
  for (Object obj: objects)
    System.out.println(obj);
}