1

我找到了一个如何将 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.
4

1 回答 1

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;
    }

}
于 2018-07-31T11:37:21.827 回答