commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From c...@honton.org
Subject Re: [configuration2]: AbstractConfiguration::getArray
Date Fri, 29 Apr 2016 15:30:39 GMT
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: user-unsubscribe@commons.apache.org
For additional commands, e-mail: user-help@commons.apache.org


Mime
View raw message