Java Convert Unknown Primitive Array to Object Arr

2020-03-12 07:16发布

I have been trying to create my own library to serialize and de-serialize primitive types from a class to xml and from xml to a class instance using reflection to examine method naming patterns and method return types.

So far I have been able to do this with all the basic primitive types but I got stuck on serializing an array of the same primitives.

For example I invoke the class method to get the array of primitives:

method.invoke(clazz, (Object[])null);

This method will return only a primitive array int[], double[], float[], char[] etc. though we don't know which one it will be.

I have tried using a generic such as

T t = (T)method.invoke(clazz, (Object[])null);
T[] t = (T[])method.invoke(clazz, (Object[])null);

But it doesn't let me cast from the primitive array to an object.

And you can't use Array.newInstance assuming we don't know the type.

Is there a way that I can convert this array of primitives to say an Object array in a generic manner.

In a generic manner meaning without needing to know or checking what the type of the array is. Or should I just cycle through all the primitive types and handle all of them separately.

I can do this both ways the only reason I want to do this in a generic manner is to cut down on the redundant code.

Thanks in advance.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-03-12 08:03
劫难
3楼-- · 2020-03-12 08:06

You can use the Array utility class

public static Object[] toObjectArray(Object array) {
    int length = Array.getLength(array);
    Object[] ret = new Object[length];
    for(int i = 0; i < length; i++)
        ret[i] = Array.get(array, i);
    return ret;
}
查看更多
Explosion°爆炸
4楼-- · 2020-03-12 08:08
Object result = method.invoke(clazz, (Object[])null);
Class<?> arrayKlazz = result.getClass();
if (arrayKlazz.isArray()) {
    Class<?> klazz = result.getComponentType();
    if (klazz == int.class) {
        int[] intArray = arrayKlazz.cast(result);
    }
}

It seems more appropiate to hold (primitive) arrays in an Object (result above).

查看更多
登录 后发表回答