Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast an Object To Long in Java

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

like image 345
Dat Tan Nguyen Avatar asked Jun 30 '16 07:06

Dat Tan Nguyen


People also ask

Can we cast object to long in Java?

longValue() is an inbuilt method of the Long class in Java which returns the value of this Long object as a long after the conversion. Parameters: This method do not take any parameters. Return Value: This method will return the numeric value represented by this object after conversion to long type.

Can you type cast an object in Java?

Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting.

How do you turn an object into an integer?

If your object is a String , then you can use the Integer. valueOf() method to convert it into a simple int : int i = Integer. valueOf((String) object);


1 Answers

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.

like image 175
sawyinwaimon Avatar answered Oct 19 '22 12:10

sawyinwaimon