> 文档中心 > java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer的解决方法

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer的解决方法

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer的解决方法

  • 问题
  • 解决方案

问题

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer
在使用hibernate5的session.createNativeQuery进行原生sql查询时,返回一个Object[]数组,利用new构造返回对象,查询时报java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer异常,异常代码如下:
java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer的解决方法
因为查询出来的obj[3]和obj[4]是利用聚合函数count查出来的,不能通过简单地(Integer)obj[3]和(Integer)obj[4]强制类型转换为Integer,经过尝试终于解决!

解决方案

  1. 先转成String类型
  2. 然后使用Integer.parseInt()或者Integer.valueOf()转换成int类型
    我的异常代码修改后为:
    Integer.valueOf(obj[3].toString()),
    Integer.valueOf(obj[4].toString())

    因为我需要的是包装类型Integer,所以用的Integer.valueOf()方法,如果你需要的是int类型,可用parseInt()方法。
    记录一下!!!O(∩_∩)O哈哈~