Last active
January 11, 2016 16:22
-
-
Save jamezrin/bbb174400aa99123ca21 to your computer and use it in GitHub Desktop.
Snippet for getting the ping of a player using reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Field; | |
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Method; | |
import org.bukkit.entity.Player; | |
import org.bukkit.plugin.Plugin; | |
public final class ReflectPing { | |
private String nmsver; | |
private Class<?> cpc, epc; | |
private Method hm; | |
private Field pf; | |
public ReflectPing(Plugin plugin) { | |
nmsver = plugin.getServer().getClass().getPackage().getName(); | |
nmsver = nmsver.substring(nmsver.lastIndexOf(".") + 1); | |
try { | |
cpc = Class.forName("org.bukkit.craftbukkit." + nmsver + ".entity.CraftPlayer"); | |
epc = Class.forName("net.minecraft.server." + nmsver + ".EntityPlayer"); | |
hm = cpc.getDeclaredMethod("getHandle", new Class<?>[] {}); | |
pf = epc.getDeclaredField("ping"); | |
} catch (NoSuchMethodException | SecurityException | NoSuchFieldException | ClassNotFoundException e) { | |
e.printStackTrace(); | |
} | |
} | |
public int getPing(Player player) { | |
try { | |
Object cp = cpc.cast(player); | |
Object ep = hm.invoke(cp); | |
return pf.getInt(ep); | |
} catch (ClassCastException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { | |
e.printStackTrace(); | |
return -1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment