Java Convert an unknown primitive array to an array of objects

I am trying to create my own library for serializing and de-serializing primitive types from a class in xml and from xml to an instance of a class using reflection to examine method naming patterns and return method types.

So far, I could do this with all the basic primitive types, but I'm stuck in serializing an array with the same primitives.

For example, I call a class method to get an array of primitives:

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

This method returns only a primitive array of int[], double[], float[], char[] , etc., although we do not know which one it will be.

I tried using a generic type like

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

But this does not allow me to convert from a primitive array to an object.

And you cannot use Array.newInstance if you don't know the type.

Is there a way I can convert this array of primitives to say an array of objects in a general way.

In a general sense, this means that you do not need to know or check the type of the array. Or should I just iterate over all the primitive types and process them all separately.

I can do this in both directions, the only reason I want to do it in a general way is to reduce redundant code.

Thanks in advance.

+6
source share
3 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; } 
+10
source

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

0
source
 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 appropriate to store (primitive) arrays in an object ( result above).

0
source

Source: https://habr.com/ru/post/946296/


All Articles