讓玩家 Ping
你可能想要對 Bukkit 不支援的 NMS 做一件非常簡單的事就是獲得玩家的 ping。這可以這樣做:
/**
* Gets the players ping by using NMS to access the internal 'ping' field in
* EntityPlayer
*
* @param player
* the player whose ping to get
* @return the player's ping
*/
public static int getPing(Player player) {
EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle();
return entityPlayer.ping;
}
如果你正在使用像 getCraftPlayer(Player)
這樣的方法,該方法將 Player 的相應 CraftPlayer 例項的例項作為 Object 返回。你可以使用如下反射來訪問資料而無需匯入依賴於版本的類:
/**
* Gets the player's ping using reflection to avoid breaking on a Minecraft
* update
*
* @param player
* the player whose ping to get
* @return the player's ping
*/
public static int getPing(Player player) {
try {
Object craftPlayer = getCraftPlayer(player);
return (int) craftPlayer.getClass().getField("ping").get(craftPlayer);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new Error(e);
}
}