Beanutils make copyproperties work on nested property of different type

Viewed 2001

I've two beans with specular properties, including nested properties of a different type, i.e.

BeanDTO {
    NestedBeanDTO nestedProperty;
}

Bean {
    NestedBean nestedProperty;
}

NestedBeanDTO {
    String name;
}

NestedBean {
    String name;
}

Now I want Apache commons

BeanUtils.copyProperties(Bean, BeanDTO) 

to copy all bean's properties including nested ones because inside have same properties too, however I got this error:

argument type mismatch - had objects of type "NestedBeanDTO" but expected signature "NestedBean"

As far I can remember is possible to configure converter behaviour with BeanutilsBean class through ConverterUtils register, but I can't figure out how.

Any suggestions?

EDIT

Solved using ConverterUtils.register():

private static class CustomBeanConverter implements Converter {

    @Override
    public <T> T convert(Class<T> aClass, Object o) {
        Object output = null;
        try {
            output = aClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(output, o);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | InstantiationException e) {
            e.printStackTrace();
        }
        return (T)output;
    }
}

and then:

BeanUtilsBean.getInstance().getConvertUtils().register(new CustomBeanConverter(), NestedBean.class);

BeanUtils.copyProperties(Bean, BeanDTO)

will automatically resolve NestedBeanDTO.name properties with NestedBean.name

0 Answers
Related