我找到了一个如何将Integer绑定到TextField的示例:
Binder<Person> b = new Binder<>();
b.forField(ageField)
.withNullRepresentation("")
.withConverter(new StringToIntegerConverter("Must be valid integer !"))
.withValidator(integer -> integer > 0, "Age must be positive")
.bind(p -> p.getAge(), (p, i) -> p.setAge(i));
问题是-没有StringToCharacterConverter,如果按原样绑定字段,是否有错误。错误是:
Property type 'java.lang.Character' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.
答案 0 :(得分:3)
您需要实现自定义转换器,这是StringToCharacterConverter
的非常简化的版本,用于获取其外观如下:
public class StringToCharacterConverter implements Converter<String,Character> {
@Override
public Result<Character> convertToModel(String value, ValueContext context) {
if (value == null) {
return Result.ok(null);
}
value = value.trim();
if (value.isEmpty()) {
return Result.ok(null);
} else if (value.length() == 1) {
Character character = value.charAt(0);
return Result.ok(character);
} else {
return Result.error("Error message here");
}
}
@Override
public String convertToPresentation(Character value, ValueContext context) {
String string = value.toString();
return string;
}
}