java.lang.Integer cannot be cast to java.lang.Long解决办法

2022/3/21 17:29:44

本文主要是介绍java.lang.Integer cannot be cast to java.lang.Long解决办法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

你好我是辰兮,本次是项目遇到的java.lang.Integer cannot be cast to java.lang.Long异常以及相对应的解决方案。

文章目录

      • 一、实战问题
      • 二、源码学习

一、实战问题

用postman测试数据报错,类型转换异常!在这里插入图片描述
如何将Integer类型转换成长整形 ?

先转成String型,再转Long;

  • 1、转String型:A.toString

  • 2、再由String型转Long 型即可

    方法1: long B = Long.valueOf(“A.toString”);

    方法2: long B = Long.parseLong(“A.toString”);

案例:用json串来传值

  @PostMapping("/updateLike")
    public CommonResponse updateLike( @RequestBody HashMap<Object, Object> map) {
        Long postId = Long.valueOf(map.get("postId").toString());
        Long userId = Long.valueOf(map.get("userId").toString());
        Integer likeStatus = (Integer) map.get("likeStatus");
        return CommonResponse.success(postReviewService.updateLike(reviewId,userId,likeStatus));
    }

再次用postman测试

在这里插入图片描述


二、源码学习

底层源码分析学习

    public static Long valueOf(String s) throws NumberFormatException
    {
        return Long.valueOf(parseLong(s, 10));
    }

我们发现valueOf的底层还是parseLong

    public static long parseLong(String s) throws NumberFormatException {
        return parseLong(s, 10);
    }

小结:先转成String型,再转Long;


Hope that we can grow and progress as soon as possible and become an excellent Java Development Engineer.



这篇关于java.lang.Integer cannot be cast to java.lang.Long解决办法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程