Solved (1.17 NMS) How to get instance of MinecraftServer?

Discussion in 'Spigot Plugin Development' started by AuroraLS3, Jul 4, 2021.

  1. Hi!

    I recently discovered that 1.17 update had broken pretty critical part of my plugin that saves data on server shutdown, but not during /reload.

    This logic was accessing MinecraftServer isStopped field to see if the server is shutting down during plugin disable.
    Code (Java):
    try {
        Class<?> minecraftServerClass = Reflection.getMinecraftClass("MinecraftServer");
        Object minecraftServer = Reflection.getField(minecraftServerClass, "SERVER", minecraftServerClass).get(null);

        return Reflection.getField(minecraftServerClass, "isStopped", boolean.class).get(minecraftServer);
    } catch (Exception | NoClassDefFoundError | NoSuchFieldError e) {
        return false;
    }
    Unfortunately it seems like SERVER field has been removed from MinecraftServer class and now isStopped can't be accessed.

    Where can I get MinecraftServer instance from?

    (Offtopic: I had another safeguard in place that stores the data via shutdown hook thread if this check fails - but oh no that broke too because now classloaders are closed on shutdown and the shutdown hook tried to load a class leading to failure of that too.)
     
    #1 AuroraLS3, Jul 4, 2021
    Last edited: Jul 4, 2021
  2. I was able to obtain instance of DedicatedServer, which extends MinecraftServer, from CraftServer
    Code (Java):
    try {
        Class<?> minecraftServerClass = Class.forName("net.minecraft.server.MinecraftServer");
        Class<?> craftServerClass = Reflection.getCraftBukkitClass("CraftServer");
        Object minecraftServer = Reflection.getField(craftServerClass, "console", minecraftServerClass).get(Bukkit.getServer());

        return (Boolean) minecraftServerClass.getMethod("isStopped").invoke(minecraftServer);
    } catch (Exception | NoClassDefFoundError | NoSuchFieldError | NoSuchMethodError e) {
        return false;
    }
     
    #2 AuroraLS3, Jul 4, 2021
    Last edited: Jul 4, 2021
    • Informative Informative x 1