让玩家 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);
    }
}