'java.lang.ClassCastException : java.lang.String cannot be cast to java.lang.Long

I'm trying to create a feed management system. I have created a simple get and post request for the servlet. I'm able to store the data in the datastore successfully as milliseconds.

But when I retrieve it

long milliseconds = entity.getProperty("timestamp");

I get some error like this

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long

What will be the reason for this issue?



Solution 1:[1]

Well, apparently in

long milliseconds = entity.getProperty("timestamp");

entity returns a String, which you assign to a long. This requires a typecast.

Note that Entity (or its superclass, PropertyContainer) explicitly states

The value returned may not be the same type as originally set via setProperty

So - what to do? If you know that you're getting a String, and you want to interpret it as a long: Use the proper conversion method (which is not a typecast).

long longValue = Long.parseLong(stringValue);

...but prepare for NumberFormatExceptions in cases where you convert actual, non-numeric Strings.

Solution 2:[2]

Apparently, you are trying to retrieve a String of number format which you want to cast to a long value. The first thing you will have to do is to check whether the value obtained from entity.getProperty("timestamp") returns a number. There's is a special library called Apache Commons Lang 3 that allows to check if your string is of numeric format. If it's the case, then it's a simple implicit cast to long value that you should do. Your code should look as follows,ASSUMING ENTITY IS NOT NULL:

 import org.apache.commons.lang3.math.NumberUtils;

   if(NumberUtils.isCreatable(entity.getProperty("timestamp")){
      long milliseconds = Long.parseLong(entity.getProperty("timestamp"));
        }
    else{    
  //print the information you want to identify the value of the property
  //for example:
   System.out.println("The following value cannot be parsed to long : " + 
  entity.getProperty("timestamp"));
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Olaf Kock
Solution 2