0

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?

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

After NumberUtils.isCreatable returns true, you need to call NumberUtils.create(...).
@k314159 I missed the Long.parseLong in my previous answer, the modification has been made

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.