我尝试以多种方式使用 java 反射来获取玩家的 ping 值。但在 100% 时,它返回 0ms。
我已经搜索了很长时间,所以...有人可以帮助我吗?
Try 1 :
public static int getPing(Player p) {
try {
Object craftPlayer = (CraftPlayer) p;
return (int) craftPlayer.getClass().getField("ping").get(craftPlayer);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException |
SecurityException e) {
throw new Error(e);
}
}
Try2 :
public static int getPing(Player p) {
EntityPlayer player = ((CraftPlayer) p).getHandle();
return player.ping;
}
Try 3 :
int ping = 0;
Class<?>[] parameterTypes = null;
Class<CraftPlayer> metadata = CraftPlayer.class;
Method[] methods = metadata.getDeclaredMethods();
for(Method method : methods) {
if(method.getName().equalsIgnoreCase("getHandle")) {
parameterTypes = method.getParameterTypes();
}
}
try {
Object entityPlayer = p.getClass().getDeclaredMethod("getHandle",
parameterTypes).invoke((CraftPlayer) p);
ping = (int) entityPlayer.getClass().getDeclaredField("ping").get(entityPlayer);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | NoSuchFieldException e) {
e.printStackTrace();
}
Try 4 :
int ping = 0;
try {
Object entityPlayer = p.getClass().getMethod("getHandle").invoke(p);
ping = entityPlayer.getClass().getField("ping").getInt(entityPlayer);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException |
SecurityException e) {
e.printStackTrace();
}
还有 3 个...(与此类似或绝对不适合使用)
我正在 VPS 托管的 1.16.4 PaperMC 服务器上测试我的插件。
也许在专用机器上会有所不同。
我尝试使用这样的“紧凑”代码:
int ping = ((CraftPlayer) p).getHandle().ping;
...但它再次返回 0ms。
请注意,我是一个真正的 Java 新手。我正在练习,以提高我的水平。
我不是在寻找最终的解决方案,而是在我的方法可行的情况下寻找答案。如果没有,这是一个好方法。