Spring CustomNumbereditor解析非数字的数字
-
12-10-2019 - |
题
我正在使用Spring CustomNumbereditor编辑器来绑定我的浮点值,并且我已经尝试过,如果在值中,有时可以解析值并且不会返回错误。
- 数字= 10 ......然后数字为10,没有错误
- 数字= 10a ......然后数字为10,没有错误
- 数字= 10a25 ......然后数字为10,没有错误
- 数字= A ......错误,因为数字无效
因此,似乎编辑器会解析该值,直到它可以省略其余的。是否有任何方法可以配置此编辑器,因此验证是严格的(因此,诸如10A或10A25之类的数字会导致错误),或者我必须构建自定义实现。我正在寻找类似于在CustomDateEditor/dateFormat中设置为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类,该类停止在第一个无效字符处解析输入字符串,因此我认为您必须扩展NumberFormat类。
首先腮红是
public class StrictFloatNumberFormat extends NumberFormat {
private void validate(in) throws ParseException{
try {
new Float(in);
}
catch (NumberFormatException nfe) {
throw new ParseException(nfe.getMessage(), 0);
}
public Number parse(String in) throws ParseException {
validate(in);
super.parse(in);
}
..... //any other methods
}
其他提示
您不能执行此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接口,甚至无效。这意味着您必须代替自己的属性编辑器。
/* 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();
}
}
我认为最优雅的方法是使用 NumberFormat.parse(String,ParsePosition)
, ,这样的事情:
public class MyNumberEditor extends PropertyEditorSupport {
private NumberFormat f;
public MyNumberEditor(NumberFormat f) {
this.f = f;
}
public void setAsText(String s) throws IllegalArgumentException {
String t = s.trim();
try {
ParsePosition pp = new ParsePosition(0);
Number n = f.parse(t, pp);
if (pp.getIndex() != t.length()) throw new IllegalArgumentException();
setValue((Float) n.floatValue());
} catch (ParseException ex) {
throw new IllegalArgumentException(ex);
}
}
...
}
不隶属于 StackOverflow