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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With