Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Convert Unknown Primitive Array to Object Array

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.

like image 518
Andrew Cumming Avatar asked May 31 '13 21:05

Andrew Cumming


1 Answers

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;
}
like image 140
Peter Lawrey Avatar answered Sep 29 '22 11:09

Peter Lawrey