mercredi 18 février 2015

How do I set an object field in an array using reflection?

I am trying to write a function which takes an object as an argument and auto-fills it from some binary, using reflection on its class.


I've written some code that looks something like this (simplified):



for (Field f: obj.getClass().getDeclaredFields())
{
try
{
if (f.getType().isPrimitive())
{
Object value = getPrimitiveValue(f.getType());
f.set(obj, value);
}
else if (f.getType().isArray())
{
Class<?> compType = f.getType().getComponentType();
Vector<Object> container = new Vector<Object>();

for (int i = 0; i < SOME_ARRAY_SIZE; i++)
{
Object item = getPrimitiveValue(compType);
container.add(item);
}
}

object[] arr = container.toArray();
f.set(obj, arr);
}
catch (Exception e)
{
//...
}
}


while getPrimitiveType reads from a static byte buffer a primitive type according to the component type.


the vector container is set with the correct values. If the component type is short, for instance, it becomes a short[] array.


However, the call f.set(obj, arr) which tries to set the value of the array field f to arr throws the exception: java.lang.IllegalArgumentException: Can not set [B field MyClass.myArrayField to [Ljava.lang.Object;


What is the correct way to do this?






Aucun commentaire:

Enregistrer un commentaire