当前位置: 首页 > 工具软件 > lang > 使用案例 >

解决java.lang.ClassCastException class java.lang.Integer cannot be cast to class java.lang.Long异常

丁雅惠
2023-12-01

下面代码段,用jdbcTemplate.queryForMap查询数据库表的ID时,虽然编译通过没有报错,但会有问题:

try {
            Map<String,Object> userPo = jdbcTemplate.queryForMap("select * from auth_user where username='" + username + "'");
            if (userPo == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }
            
            Long id = (Long)userPo.get("id");  //这行代码会报类型转换错误
            String password = (String)userPo.get("password");

            //用户权限
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from auth_user_role where user_id=" + id);
            if (!CollectionUtils.isEmpty(list)) {
                for (Map<String,Object> po : list) {
                    String roleCode = (String)po.get("role_code");
                    authorities.add(new SimpleGrantedAuthority(roleCode));
                }
            }
            return new User(username, password, authorities);
        }catch(Exception ex){
            ex.printStackTrace();
        }

用Postman调用API报错如下:

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')
...

解决办法:

//用下面这行代码代替原来的代码(Long)userPo.get("id"),直接转换为Long类型
Long id = ((Integer)userPo.get("id")).longValue();
 类似资料: