samedi 30 avril 2022

Reflection: how to assign an Array to Object's field

I use readValue of Jackson framework which returns Object[] (valueField). And I have an object bean with the field List<T> repository (targetField). I need to assign Array to that List, but the best I reached is that targetField holds 1 element which is the whole Array itself (look at attached image).

I tried to cast Object[] to List but I got ImmutableCollectionList instead of common array and targetField is just assigned the reference instead of value. New ArrayList() does not help. I tryed field.set(bean, valueField) with no result and ran into Array.newInstance(), but did not managed to implement it correctly in that case. I'm puzzled

private void installFieldConfig(Object bean, Field field) {
    ConfigProperty configProperty = field.getAnnotation(ConfigProperty.class);
    File file = configProperty.configFileNameEnum().getConfigFile();

    Object targetField;
    Object valueField;
    if (AbstractDao.class.isAssignableFrom(bean.getClass())) {
        Class<?> singleClazz = ((AbstractDao<?>) bean).getTypeParameterClass();
        Class<?> arrayClazz = Array.newInstance(singleClazz, 0).getClass();
        try {
            targetField = field.get(bean); //successfully get the bean's field in which I want inject new value (ArrayList<T>)
            valueField = objectMapper.readValue(file, arrayClazz); //this is Jackson method, returns T[] 
            targetField = List.of(valueField); //here is the trouble
            field.set(bean, valueField); //also trouble
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Debug overview image





Aucun commentaire:

Enregistrer un commentaire