stargate stargate - 4 months ago 35
Java Question

Integer cannot be cast to Float

Currently I am working a plugin that involves saying locations in the database, and then caching them

onEnable()
. However, I run into this error - "java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float" when I try and phrase a location. Here is my phrase method:

private HubLocation formatLocation(DBObject object){
World world = Bukkit.getWorld((String)object.get("world"));
Location location = new Location(world, (double)object.get("x"), (double)object.get("y"), (double)object.get("z"),
(float)object.get("yaw"), (float)object.get("pitch"));
return new HubLocation((String)object.get("name"), location);
}


Hope someone can help,
Thanks!

Answer

This is a common issue with MonogDB doing strange type conversions. The safest solution is to always use the Number type for values from the database:

private HubLocation formatLocation(DBObject object){
    World world = Bukkit.getWorld(object.get("world").toString());
    Location location = new Location(world, 
        ((Number)object.get("x")).doubleValue(), 
        ((Number)object.get("y")).doubleValue(), 
        ((Number)object.get("z")).doubleValue(),
        ((Number)object.get("yaw")).floatValue(), 
        ((Number)object.get("pitch")).floatValue());
    return new HubLocation(object.get("name").toString(), location);
}