Skip to content

Instantly share code, notes, and snippets.

@jamezrin jamezrin/ReflectPing.java
Last active Jan 11, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.