Unpacking an Array using reflection

后端 未结 2 672
耶瑟儿~
耶瑟儿~ 2021-01-02 05:01

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 genera

2条回答
  •  生来不讨喜
    2021-01-02 05:52

    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.

    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

    Test: http://ideone.com/iHQKY

提交回复
热议问题