f:convertNumber on Double: ClassCastException

廉价感情. 提交于 2019-12-04 20:39:05

I've looked at the sourcecode of the NumberConverter of both JSF 2.2 and 2.3 and noticed no serious differences (just comments, copyrights etc). I isolated the code that does the actual conversion and isolated this in some very small plain java code.

NumberFormat nf = NumberFormat.getNumberInstance(Locale.getDefault());

System.out.println(nf.getClass());
System.out.println(Double.class.isAssignableFrom(BigDecimal.class));
System.out.println(nf.parse("10,0")+ " : " + nf.parse("10,0").getClass());
System.out.println(nf.parse("10,1")+ " : " + nf.parse("10,1").getClass());
System.out.println(nf.parse("10.0")+ " : " + nf.parse("10.0").getClass());
System.out.println(nf.parse("10.1")+ " : " + nf.parse("10.1").getClass());

Which results in the folowing output.

class java.text.DecimalFormat
false
100 : class java.lang.Long
101 : class java.lang.Long
10 : class java.lang.Long
10.1 : class java.lang.Double

I initially ran this on JDK 8, but also tried 7 later, both with the same results.

So I'd be inclined to draw the conclusion that it is not JSF that causing problems (although I'd say that since the converter uses the expected type to do some checking it would not be strange to return the expected type and not the type returned by the NumberFormat.

But when setting the parseBigDecimal to true

((DecimalFormat)nf).setParseBigDecimal(true);

And running the same 'tests', there is no loss in presision like mentioned in the converter and the output is

100 : class java.math.BigDecimal
101 : class java.math.BigDecimal
10.0 : class java.math.BigDecimal
10.1 : class java.math.BigDecimal

But this cannot be cast to a Double either. So I'd personally start looking into the BeanValidator code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!