Jorge,

You could create a different named method for each primitive array type. Would be a pain to use in a generic fashion.

Play with the following sample code to see why the return type
needs to be Object.

regards,
chas



import java.lang.reflect.Array;
import java.lang.reflect.Field;

import org.junit.Test;

public class GenericCastTest {

    @SuppressWarnings("unchecked")
    public <T> T[] newEmptyArray(Class<T> cls) {
        return (T[]) Array.newInstance(cls, 0);
    }

    /**
     * Can't overload method because type erasure is same
     */
    public int[] newEmptyIntArray(Class<int[]> cls, String key) {
        return (int[]) Array.newInstance(cls, 0);
    }

    public static class ConfigPojo {
        public int[] intParam;
    }

    @Test(expected=ClassCastException.class)
public void useObjectReturn() throws IllegalArgumentException, IllegalAccessException {
        // won't compile
        // int[] empty = newEmptyArray(Integer.TYPE);

        ConfigPojo cp = new ConfigPojo();
        fillWithEmptyArrays(cp);
    }

private void fillWithEmptyArrays(Object cp) throws IllegalArgumentException, IllegalAccessException {
        for(Field field : cp.getClass().getFields()) {
            if(field.getType().isArray()) {
field.set(cp, newEmptyArray(field.getType().getComponentType()));
            }
        }
   }
}



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to