开箱使用反射阵列 [英] Unpacking an Array using reflection

查看:104
本文介绍了开箱使用反射阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个反映对象的字段解压的数组我得到。
我一般字段的值设置为对象。如果它是一个数组,那么我想我一般对象转换为一个数组(不管其类型),并提取其内容

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. 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);
        }

在我unpackArray方法,我都试过铸造对象值java.util.Arrays中,java.reflect.Array和Array []但是每次都没有让我。

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.

有没有一种方法,我可以投我对象到一个通用的阵列?

Is there a way I can cast my Object to a generic array?

非常感谢
山姆

Many Thanks Sam

推荐答案

唯一的父类的所有数组是Object。

The only parent class of all arrays is Object.

要提取一个数组的值作为对象[] 即可使用。

To extract the values of an array as an Object[] you can use.

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;
}

这篇关于开箱使用反射阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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