9

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.

0

3 Answers 3

15

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It worked perfectly. I never thought that I could access the object as an array. Thank you.
0

Does java.lang.reflect.Array.get() do what you want?

2 Comments

You also need the getLength()
It would be my next step. This would allow me to get an item from the array but I still need to know how to store it in a proper array first.
0
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).

2 Comments

How will this help get an Object[] from the result?
Object[] is already answered. But solving the problem of serialization with Object[] for an int[], double[] etcetera seems a bit going too far. A general array should be held in an Object. I want to suggest that without too large emphasis. If an Object[] is wished - fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.