今天的博客主题:
Java开发路上的小坑坑 ——》int 和 Integer 作为接收参数类型,参数长度不能大于10?
int 和 Integer 作为接收参数类型,参数长度不能大于10?
What???
就问问小菜鸟惊讶不惊讶,大佬略过......
public static void main(String[] args) {
testint(1111111111); // 10个1 compile success
testInteger(1111111111); // 10个1 compile success
testint(11111111111);// 11个1 compile error
testInteger(11111111111);// 11个1 compile error
}
public static void testint(int bizId){
System.out.println(bizId);
}
public static void testInteger(Integer bizId){
System.out.println(bizId);
}如果你在你的 Controller 使用 Integer 来接收参数,请求结果 400 参数类型不合法
@RequestMapping(value = "/testInteger", method = RequestMethod.POST)
public ApiResponse testInteger(Integer bizId) {
try {
System.out.println(bizId);
} catch (IllegalArgumentException e) {
return ApiResponse.fireError(e.getMessage(), null);
}
return ApiResponse.fireSuccess(bizId);
}浏览器请求:http://localhost:6101/saleEdit/testInteger?bizId=11111111111

后台异常信息:
2020-04-22 13:50:21.986 WARN 9344 --- [ XNIO-1 task-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "11111111111"]
Why???
因为 Integer 最大值的范围是:2的31次方 - 1 = 2147483648 - 1 = 2147483647
21亿+,长度也就是10位,超过11位,就大于 Integer 最大值的范围了。大1 都不行,编译时就不通过。
/**
* A constant holding the minimum value an {@code int} can have, -2<sup>31</sup>.
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
* A constant holding the maximum value an {@code int} can have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;Controller 的方法是不建议用 Integer 或 Long 来接收参数的。
大佬看见标题都知道咋回事了,,,小菜鸟还是差的甚远,,,加油吧
版权声明:本文为weixin_46129103原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。