Skip to content

Instantly share code, notes, and snippets.

@jamezrin
Last active January 11, 2016 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamezrin/bbb174400aa99123ca21 to your computer and use it in GitHub Desktop.
Save jamezrin/bbb174400aa99123ca21 to your computer and use it in GitHub Desktop.
Snippet for getting the ping of a player using reflection
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