java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long
By:Roy.LiuLast updated:2019-08-11
Below example, the jdbcTemplate.queryForList returns an object of Integer and we try to convert it into a Long directly:
public List<Customer> findAll() { String sql = "SELECT * FROM CUSTOMER"; List<Customer> customers = new ArrayList<>(); List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); for (Map row : rows) { Customer obj = new Customer(); obj.setID(((Long) row.get("ID"))); // the object is an Integer obj.setName((String) row.get("NAME")); customers.add(obj); return customers;
Output
Caused by: java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap') at com.mkyong.misc.CustomerRepository.findAll(CustomerRepository.java:73) at com.mkyong.misc.CustomerRepository$$FastClassBySpringCGLIB$$7fc6ff36.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) at com.mkyong.misc.CustomerRepository$$EnhancerBySpringCGLIB$$f96f7027.findAll(<generated>) at com.mkyong.StartApplication.startCustomerApp(StartApplication.java:103) at com.mkyong.StartApplication.run(StartApplication.java:72) at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813)
Solution
To solve it, convert it back to the original Integer and cast it to Long
obj.setID(((Integer) row.get("ID")).longValue()); //obj.setID(((Long) row.get("ID")));
Java basic:
Integer num = 1; Long numInLong = num.longValue(); // Integer to Long Long numInLong2 = Long.valueOf(num); // Integer to Long
From:一号门
COMMENTS