[java bug]Optional int parameter ‘xxx‘ is present but cannot be translated into a null value...

小咪咪 2024-02-05 13:35 144阅读 0赞

背景:

在测试按照关键词搜索的功能时,前端不传递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即可。

修改前

  1. @RequestMapping("/select")
  2. public ModelAndView select(int cid, String name){
  3. ModelAndView modelAndView = new ModelAndView();
  4. Product cooker = productService.findOne(cid);
  5. modelAndView.addObject("cooker", cooker);
  6. modelAndView.setViewName("/frontdesk/cooker");
  7. return modelAndView;
  8. }

修改后

  1. @RequestMapping("/select")
  2. public ModelAndView select(Integer cid, String name){
  3. ModelAndView modelAndView = new ModelAndView();
  4. Product cooker = productService.findOne(cid);
  5. modelAndView.addObject("cooker", cooker);
  6. modelAndView.setViewName("/frontdesk/cooker");
  7. return modelAndView;
  8. }

原因分析:

在java中,int和Integer这两个数据类型都可以用来表示整数类型。但int只是一个基本数据类型,而Integer是一种对象类型,是int的包装类。虽然int可以满足大部分情况,但在此例中,int无法处理空值(null),而Integer却可以将空值(null)作为一个有效值来表示。
除此以外,在以下几种情况中,都应该使用Integer包装类而不是int基本数据类型

  • 集合类(list、set、map) :这些集合中要求存储的对象而不是数据类型
  • API兼容性: 对于一些要求整数是对象的java库和框架,使用Integer更能满足条件
  • 对象特性和方法拓展:因为Integer是一个类,提供了compareTo() toString()等方法,可以对整数实现更多的操作

发表评论

表情:
评论列表 (有 0 条评论,144人围观)

还没有评论,来说两句吧...

相关阅读