lundi 22 janvier 2018

Fill array(value of a field) with the elements of a List

I have a field of an array type, which should be set/filled to an array containing the elements of a list of the same type. So far I tried out:

  • to create an Object array and fill it with the elements of the list
  • cast the fields value to an Object array and fill its values

    //the generic type of List is the fields type without the array
    if(field.getType().isArray() && obj instanceof List) {          
        List<?> list = (List<?>) obj;
        Object[] array = new Object[list.size()];
    
        for(int x = 0; x < array.length; x++) {
            array[x] = list.get(x);
        }
    
        obj = field.getType().cast(array);
    }
    
    field.set(module, obj);
    
    

but everything leads to a ClassCastException: [D cannot be cast to [Ljava.lang.Object;
My question is: Is it possible to fill the array of the field with the elements of the List? If yes how?





Aucun commentaire:

Enregistrer un commentaire