简体   繁体   中英

java.lang.Long cannot be cast to java.lang.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.

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);

This is confusing.

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; 

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; 

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.

If you are not sure what number type the object would be then I would recommend using this code snippet:

double d = 0.0;
if (obj instanceof Number) {
    d = ((Number) obj).doubleValue();
}

First check if the Object is instanceof Long and then call valueOf of Long obejct

Snippet:

static double convertDouble(Object longValue){
        double valueTwo = -1; // whatever to state invalid!

        if(longValue instanceof Long) 
           valueTwo = ((Long) longValue).doubleValue();

        System.out.println(valueTwo);
          return valueTwo;
     }

You try to convert Object to double, since your parameter of convertDouble is of Type object. Thus the auto-unboxing will not work. There would be two solutions: first, cast the Object to Long (checking with instanceof) second, use Long as Parameter

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

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

If you want to convert different types of arguments withing the convertDouble method, you may check with instanceof and then convert the Object to the type, you eventually have

This method is not very performatic but converts any Number Object to common java.lang Object (Byte, Short, Integer, Long, Float and Double).

This uses reflection to call methods of Number class (shotValue(), intValue(), etc).

Unfortunatly, does not exists integerValue Method name, thus I'm using a replace string to convert integer to int.

I hope was help.

public <T extends Number> T cast(Number value, Class<T> toClass) {

    try {
        String methodName = toClass.getSimpleName().toLowerCase().replace("integer", "int") + "Value";
        Method m = Number.class.getMethod(methodName);
        return (T) m.invoke(value);
    } catch (Exception ex) {
    }
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM