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
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With