gpt4 book ai didi

java - Spring CustomNumberEditor 解析不是数字的数字

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:14 25 4
gpt4 key购买 nike

我正在使用 Spring CustomNumberEditor 编辑器来绑定(bind)我的浮点值,并且我已经试验过,如果值不是数字,有时它可以解析该值并且不会返回任何错误。

  • number=10 ......那么这个数字就是10,没有错误
  • number=10a ......那么这个数字就是10,没有错误
  • number=10a25 ......那么这个数字就是10,没有错误
  • number=a ......错误,因为数字无效

所以看起来编辑器会解析值直到它可以并忽略其余部分。有什么方法可以配置此编辑器以便验证是严格的(因此像 10a 或 10a25 这样的数字会导致错误)或者我是否必须构建我的自定义实现。我正在寻找类似于在 CustomDateEditor/DateFormat 中将 lenient 设置为 false 这样的日期无法解析为最可能的日期。

我注册编辑器的方式是:

@InitBinder
public void initBinder(WebDataBinder binder){
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setGroupingUsed(false);
binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}

谢谢。

最佳答案

您不能使用 NumberFormat 执行此操作。

文档清楚地说明了这一事实:

/**
* Parses text from the beginning of the given string to produce a number.
* The method may not use the entire text of the given string.
* <p>
* See the {@link #parse(String, ParsePosition)} method for more information
* on number parsing.
*
* @param source A <code>String</code> whose beginning should be parsed.
* @return A <code>Number</code> parsed from the string.
* @exception ParseException if the beginning of the specified string
* cannot be parsed.
*/
public Number parse(String source) throws ParseException {

当您接受此 API 时,编写一个执行您想要的操作并实现 NumberFormat 接口(interface)的解析器甚至是无效的。这意味着您必须改用自己的属性编辑器。

/* untested */
public class StrictNumberPropertyEditor extends PropertyEditorSupport {

@Override
public void setAsText(String text) throws IllegalArgumentException {
super.setValue(Float.parseFloat(text));
}

@Override
public String getAsText() {
return ((Number)this.getValue()).toString();
}
}

关于java - Spring CustomNumberEditor 解析不是数字的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4726861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com