简体   繁体   中英

Bukkit - Why does casting to Damageable work?

From Bukkit 1.6.4 on there was another way to handle to players life, the life is stored as double from now on. To be compatible to older plugins the Player.getHealth() method is ambigious, there are:

@Deprecated
public int getHealth();
public double getHealth();

I was trying to use Player.getHealth() and ended up with an error. I searched for a solution, but things like double d = (double) player.getHealth() or double d = new Double(player.getHealth()); still throw the error The method getHealth() of Player is ambigious (I am using Eclipse btw.). But after some search I also found this:

Damageable d = player; //because player is a Damageable
double health = d.getHealth();
//the method called is the "new one", which returns a double

I don't understand why this works, because I took a look at Damageable and the two ambigious methods are already defined in Damageable. The error described above should also occur here. Where am I wrong? What am I missing?

Thanks in advance.

This is because in Minecraft 1.6.4 and up, the health is now stored in a float. Bukkit decided to use a double to protect against a future change from float to double. If you don't use NMS anywhere, use only bukkit , and not craftbukkit , as this will make it so that you can just do double d = player.getHealth(); . Otherwise if you need craftbukkit , you could put bukkit higher than craftbukkit in your build hierarchy.

Damageable.getHealth() is a method from Bukkit, so it is not deprecated, while Player.getHealth() is a method in CraftBukkit (CraftBukkit uses code mostly from the original Minecraft server, (called NMS), so It IS deprecated. Although if you were to remove CraftBukkit from your build path, or put Bukkit above it, then Player.getHealth() would work.

Bukkit deprecated the .getHealth() methods that use integers, although they still work, but they will be removed soon. So, at the moment, you need to use double health = ((Damageable) player).getHealth();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM