9

When using this code with DatastoreService I get ClassCastException Long acnnot be cast to integer in fromEntity. Is it normal behaviour? (I get this behaviour when debugging on local computer with google plugin for eclipse)

class UserData {
    private int _integerval = 0;
    private String _stringval = "";
    public Entity getEntity() {
        Entity ret = new Entity( "User", key );
        ret.setProperty( "property1", _integerval );
        ret.setProperty( "property2", _stringval );
        return ret;
    }

    public static UserData fromEntity( Entity ent ) {
        UserData ret = new UserData();
        ret._integerval = (Integer)ent.getProperty("property1");
        ret._stringval = (String)ent.getProperty("property2");
        return ret;
    }
}

Do I always have to catch this exception like this:

try
{
    ret._integerval = (Integer)ent.getProperty("property1");
}
catch( ClassCastException ex ) {
    Long val = (Long)ent.getProperty("property1");
    ret._integerval = val.intValue(); 
}

Or maybe all the numeric values are stored as long only? Do I have to change _integerval type to long to avoid this exceprion?

Dmitry
  • 416
  • 1
  • 6
  • 13

5 Answers5

6

Use int instead of Integer while casting.

ret._integerval = (int)ent.getProperty("property1");

Edit:

The following is included in the setProperty API.

As the value is stored in the datastore, it is converted to the datastore's native type. This may include widening, such as converting a Short to a Long.

So your int data is being converted to datastore's native type as Long. Cast using long or Long.

Jayamohan
  • 12,734
  • 2
  • 27
  • 41
  • The same. Get java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer. – Dmitry Mar 06 '13 at 11:51
6

Create a new Integer :

Integer property = new Integer(entity.getProperty("propertyKey").toString());
d.danailov
  • 9,594
  • 4
  • 51
  • 36
1

If you want to use int in your programm then this works ok:

int i = (int) (long) entity.getProperty(propertyName);

Still be sure that the number gets into the int-range (discussed here).

Community
  • 1
  • 1
sberezin
  • 3,266
  • 23
  • 28
1

As reported in the official documentation

As the value is stored in the datastore, it is converted to the datastore's native type. This may include widening, such as converting a Short to a Long.

So

  • Set as int but cast it to long because for some reason the datastore behaviour in local environment is different and it stores integer also.
  • Get the Long and use .intValue()

    public int get() {
        return ((Long) entity.getProperty(FIELD)).intValue(); 
    }
    
    public void set(int value) {
        entity.setProperty(FIELD, (long)value); 
    }
    
Angelo Nodari
  • 365
  • 7
  • 14
0

Integer values are saved as Long, so app engine will always return Long, i was confused myself but then i saw this

Dan Levin
  • 718
  • 7
  • 16