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?
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
.
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