When I define a bean class with a custom type property, how to use BeanWrapper to fill the value.
public class BetweentValue<T>{
private T min;
private T max;
// setter and getter
}
pbulic class Bean{
private BetweenValue<LocalDateTime> betweemValue;
// setter and getter
}
public void Main{
public static void main(String[] args){
Bean bean = new Bean();
final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(bean);
beanWrapper.setAutoGrowNestedPaths(true);
beanWrapper.setPropertyValue("betweenValue.min","2023-04-12 00:00:00");
System.out.println(bean.betweenValue.min);
}
}
Comment From: haitaoss
You can set up ConversionService for BeanWrapperImpl to handle type conversions
public void Main{
public static void main(String[] args){
Bean bean = new Bean();
final BeanWrapperImpl beanWrapper = new BeanWrapperImpl(bean);
beanWrapper.setConversionService(new DefaultFormattingConversionService()); // It can also be obtained from the container
beanWrapper.setAutoGrowNestedPaths(true);
beanWrapper.setPropertyValue("betweenValue.min","2023-04-12 00:00:00");
System.out.println(bean.betweenValue.min);
}
}
Comment From: iimik
This way can set the value of '2023-04-12 00:00:00' into the betweenValue.min property, but the value type is String, I wanted it is a LocalDateTime. @haitaoss
Comment From: haitaoss
If possible, you can avoid using generics and change to specific types, and then add custom conversion rules to solve this problem
public class BetweentValue {
private LocalDateTime min;
}
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
conversionService.addConverter(new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
});
Comment From: rstoyanchev
Thanks for getting in touch, but it feels like this is a question that would be better suited to Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use the issue tracker only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add some more details if you feel this is a genuine bug.