[java bug]Optional int parameter ‘xxx‘ is present but cannot be translated into a null value...
背景:
在测试按照关键词搜索的功能时,前端不传递cid的值,所以cid为空,Idea控制台报错如下Optional int parameter 'cid' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
这里的错误大体意思是:可选的int参数“cid”存在,但由于被声明为基元类型,因此无法转换为null值。考虑将其声明为相应基元类型的对象包装器。
解决方案
按照以上的错误消息,只需要将 cid 的 数据类型由 int 改为 Integer即可。
修改前
@RequestMapping("/select")
public ModelAndView select(int cid, String name){
ModelAndView modelAndView = new ModelAndView();
Product cooker = productService.findOne(cid);
modelAndView.addObject("cooker", cooker);
modelAndView.setViewName("/frontdesk/cooker");
return modelAndView;
}
修改后
@RequestMapping("/select")
public ModelAndView select(Integer cid, String name){
ModelAndView modelAndView = new ModelAndView();
Product cooker = productService.findOne(cid);
modelAndView.addObject("cooker", cooker);
modelAndView.setViewName("/frontdesk/cooker");
return modelAndView;
}
原因分析:
在java中,int和Integer这两个数据类型都可以用来表示整数类型。但int只是一个基本数据类型,而Integer是一种对象类型,是int的包装类。虽然int可以满足大部分情况,但在此例中,int无法处理空值(null),而Integer却可以将空值(null)作为一个有效值来表示。
除此以外,在以下几种情况中,都应该使用Integer包装类而不是int基本数据类型
- 集合类(list、set、map) :这些集合中要求存储的对象而不是数据类型
- API兼容性: 对于一些要求整数是对象的java库和框架,使用Integer更能满足条件
- 对象特性和方法拓展:因为Integer是一个类,提供了
compareTo()
toString()
等方法,可以对整数实现更多的操作
还没有评论,来说两句吧...