java.lang.Long无法强制转换为java.lang.Double [英] java.lang.Long cannot be cast to java.lang.Double

查看:152
本文介绍了java.lang.Long无法强制转换为java.lang.Double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,它将对象作为输入,如果输入是instanceOF Long,则将值转换为double值。下面是代码:

I have a method which takes object as an input and if the input is instanceOF Long then converting the value to double value. Below is the code :

public static void main(String[] args) {
    Long longInstance = new Long(15);
    Object value = longInstance;
    convertDouble(value);
}

static double convertDouble(Object longValue){
    double valueTwo = (double)longValue;
    System.out.println(valueTwo);
    return valueTwo;
}

但是当我执行上面的代码时,我得到的是异常:

but when I am executing the above code I am getting below exception :

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
at com.datatypes.LongTest.convertDouble(LongTest.java:12)
at com.datatypes.LongTest.main(LongTest.java:8)

请告诉我为什么它给我例外。

Kindly let me know why its giving me exception.

但是如果直接尝试将Long对象转换为double然后没有classCast的例外。

But if directly try to cast Long object into double then there is no Exception of classCast is coming.

Long longInstance = new Long(15);
    double valueOne = (double)longInstance;
    System.out.println(valueOne);

这令人困惑。

推荐答案

在JLS中找到解释, https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.5

表格下5.1。将转换投射到基本类型

Found explaination in JLS, https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.5
Under Table 5.1. Casting conversions to primitive types

    Long l = new Long(15);
    Object o = l;

将对象类型转换为基元时,它将缩小然后取消装箱

When converting Object Type to primitive then it will narrowing and then unboxing.

    double d1=(double)o; 

在上述声明中我们试图将对象缩小为双倍,但自此实际值为Long ,因此在运行时它会抛出 ClassCastException ,因为 5.1.6中定义的缩小转换规则。缩小参考转换

in above statement we are trying to narrow Object to Double, but since the actual value is Long so at runtime it throws ClassCastException, as per narrowing conversion rule defined in 5.1.6. Narrowing Reference Conversion

将长类型转换为双精度时,它会执行取消装箱然后加宽

When converting Long Type to double, it will do unboxing and then widening.

    double d2 =(double)l; 

它首先通过调用longvalue()方法取消装箱Long值,然后从long扩展到long double,可以没有错误。

it will first unbox the Long value by calling longvalue() method and then do the widening from long to double, which can be without error.

这篇关于java.lang.Long无法强制转换为java.lang.Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆