简体   繁体   English

使用反射解压缩数组

[英]Unpacking an Array using reflection

I am trying to unpack an array I obtain from reflecting an objects fields. 我正在尝试解压缩从反射对象字段获得的数组。 I set the value of the general field to an Object. 我将常规字段的值设置为Object。 If it is an Array I then want to cast my general Object to an array (no matter what its type) and extract its content 如果它是一个数组,那么我想将我的一般对象转换为一个数组(无论它的类型)并提取其内容

fields[i].setAccessible(true);
        String key = fields[i].getName();
        Object value = fields[i].get(obj);

        if (value.getClass().isArray()){
            unpackArray(value);
        }

In my unpackArray method, I have tried casting the Object Value to java.util.Arrays, java.reflect.Array and Array[] but each time it is not letting me. 在我的unpackArray方法中,我尝试将Object Value转换为java.util.Arrays,java.reflect.Array和Array [],但每次都不让我。

Is there a way I can cast my Object to a generic array? 有没有办法将我的Object转换为通用数组?

Many Thanks Sam 非常感谢Sam

The only parent class of all arrays is Object. 所有数组的唯一父类是Object。

To extract the values of an array as an Object[] you can use. 要将数组的值提取为Object[]您可以使用。

public static Object[] unpack(Object array) {
    Object[] array2 = new Object[Array.getLength(array)];
    for(int i=0;i<array2.length;i++)
        array2[i] = Array.get(array, i);
    return array2;
}

Unfortunately primitive Arrays and Object Arrays do not have a common array class as ancestor. 不幸的是,原始数组和对象数组没有共同的数组类作为祖先。 So the only option for unpacking is boxing primitive arrays. 所以解包的唯一选择是装箱原始数组。 If you do null checks and isArray before calling this method you can remove some of the checks. 如果在调用此方法之前执行空检查和isArray,则可以删除一些检查。

public static Object[] unpack(final Object value)
{
    if(value == null) return null;
    if(value.getClass().isArray())
    {
        if(value instanceof Object[])
        {
            return (Object[])value;
        }
        else // box primitive arrays
        {
            final Object[] boxedArray = new Object[Array.getLength(value)];
            for(int index=0;index<boxedArray.length;index++)
            {
                boxedArray[index] = Array.get(value, index); // automatic boxing
            }
            return boxedArray;
        }
    }
    else throw new IllegalArgumentException("Not an array");
}

Test: http://ideone.com/iHQKY 测试: http//ideone.com/iHQKY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM