Cast an Object To Long in Java
Asked Answered
C

9

16

I am trying to convert a Object type to Long type in Java and I got as:

public static Long castObjectToLong(Object object) {
    return ((Long)object).longValue();

When I run, it throws ClassCastException

Cassondracassoulet answered 30/6, 2016 at 7:9 Comment(9)
What do you expect from casting an Object to Long?Tarton
How about public static long castObjectToLong( ... Junitajunius
Return type is missing in your method!Oquendo
What means it does not work well?Hiding
After edit: Please be more specific on your perception of "not work well"? Does it throw exceptions? Don't you get the values that you expect?Junitajunius
Refer #2351689Oquendo
I have a class to convert Object to many types but I get stuck when converting to Long It throws ClassCastExceptionCassondracassoulet
Casting an Object does not change its class. It just tells the compiler that is of the class you want it cast to. If the object you are trying to cast to Long is not already a Long you will get a ClassCastExceptionNog
https://mcmap.net/q/747409/-how-to-convert-object-to-long-data-type-javaVersus
N
37

when you write return ((Long)object).longValue(); causes ClassCastException because Object is not Long. That I mean is if Object o = new Long(), then you can make cast ((Long)object). This is the example I wrote is just like:

public class Test {

    public static void main(String args[]){
        System.out.println(convertToLong(10));
    }
    
    public static Long convertToLong(Object o){
        String stringToConvert = String.valueOf(o);
        Long convertedLong = Long.parseLong(stringToConvert);
        return convertedLong;
        
    }

}

I convert Object to String first.Then String to Long.Please see this code is ok to use for you or not.

Numbles answered 30/6, 2016 at 7:29 Comment(0)
R
7

You got ClassCastException because may be you were trying to convert java.lang.Integer into java.lang.Long which cannot be done directly.

Try to convert object to String and then pass it as an argument to constructor of Long

public static Long castObjectToLong(Object object) {
   return new Long(object.toString());
}
Rabato answered 12/7, 2018 at 7:21 Comment(2)
It is rarely appropriate to use this constructor. docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/…Garnes
Long constructor are deprecated as of Java 9+. Use Long.valueOf(object.toString()) insteadCespitose
D
6

you can try like this:

 public class HelloWorld{
public static Long castObjectToLong(Object object) {
  return Long.parseLong(object.toString());
       }
    public static void main(String []args){
       System.out.println("Hello World");
       Object object=1234;
        System.out.println(castObjectToLong(object));
    }
}
Dimity answered 30/6, 2016 at 7:37 Comment(0)
D
5

The following code may help:

public class CastObjectToLong {
    public Long castLongObject(Object object) {
        Long result = 0l;
        try {
            if (object instanceof Long)
                result = ((Long) object).longValue();
            else if (object instanceof Integer) {
                result = ((Integer) object).longValue();
            } else if (object instanceof String) {
                result = Long.valueOf((String) object);
            }
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("============= cannot cast");
            // do something
        }
        return result;
    }

    public static void main(String... args) {
        CastObjectToLong castObjectToLong = new CastObjectToLong();
        Object object1 = 12; // Integer
        Object object2 = "12"; // String
        Object object3 = 12l; // String
        Object object4 = "abc"; // String

        castObjectToLong.castLongObject(object1);
        castObjectToLong.castLongObject(object2);
        castObjectToLong.castLongObject(object3);
        castObjectToLong.castLongObject(object4); // exception here
    }

}

Outputs:

12

12

12

============= cannot cast

Dewy answered 7/9, 2016 at 10:15 Comment(1)
I like this answer. I do not understand why people upvote answers with overused string operations. It is ridiculous and inefficient. BTW, here instead of result = ((Long) object).longValue() it can be just result = (Long) object;.Cram
K
1

In your code, ClassCastException is being thrown because Object is not Long. There is also a probability of encountering a NullPointerException, in case your object is null.

Hence the best solution would be to do a null check on your object , then convert it to String using either String.valueOf or toString() and then parse it to Long.

The difference between String.valueOf(object) and object.toString() won't matter here, as the former returns null when the object is null where as the latter throws NullpointerException.

Kathernkatheryn answered 21/3, 2022 at 11:28 Comment(0)
H
0

I love to use BigDecimal. Simple and error-free. Even if your object contains a decimal it will handle it.

long l = new BigDecimal(String.valueOf(object).setScale(0).longValue());
Humorous answered 13/12, 2020 at 6:38 Comment(0)
P
0

Long.parseLong((String.valueOf(object)))

Permanence answered 6/3, 2021 at 11:1 Comment(0)
W
0

This is because you are returning long value instead of Long.longValue() method which you have used will give long value only but you don't want primitive data type value instead you want Long so simply casting it will work!! i.e return (Long)object instead of ((Long)object).longValue();

Winston answered 1/8, 2021 at 15:48 Comment(0)
D
0

The Simplest way to do the conversion from object to Long is:

public class Test {

    public static void main(String[] args) {
        Object a=15;
        
        System.out.println(Long.parseLong(a.toString()));
    }
}

output:15

Digression answered 4/8, 2022 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.