例如,如果我希望为 java.util.Map 的所有实例注册一个转换器,有没有办法做到这一点:
new BeanUtilsBean().getConvertUtils().register(new MyConverter(), Map.class);
MyConverter#convert()对于 Map 的任何实例(例如 HashMap),该方法会在哪里调用?
这样做的背景是我使用 BeanUtils 从数据库中填充各种不同的 bean。它们的一些属性是实现特定接口的枚举,并且需要自定义例程来设置它们的值。我希望为相关接口的所有实现注册一个转换器类,但找不到这样做的方法,所以最终不得不通过检查 bean 中每个属性的类来动态完成它和如果它们恰好是此接口的实例,则注册我的转换器类:
BeanUtilsBean b = new BeanUtilsBean();
Class< ? > propertyType = pu.getPropertyType(this, setterName);
if (isImplementationOfMyInterface(propertyType)) {
b.getConvertUtils().register(new MyConverter(), propertyType);
}
b.setProperty(this, setterName, value);
这似乎很讨厌,我敢肯定一定有更好的方法来做到这一点?