public static void setMOTD(final String motd) throws Exception {
final Field field = MinecraftServer.class.getDeclaredField("motd");
final Field server = CraftServer.class.getDeclaredField("console");
field.setAccessible(true);
server.setAccessible(true);
MinecraftServer instance = (MinecraftServer) server.get(CraftServer.class);
field.set(instance, motd);
}
My goal with this is to change the Message of the day on a minecraft server (running craftbukkit). To do this I need to change a non-static field motd. I am doing all of this with a plugin so I can’t get the instance for the MinecraftServer. The second last line was my attempt at doing this with reflection however it failed. I don’t have access to change the MinecraftServer class or CraftServer because they are in an external library.
motd and console are both non-static fields.
motd is a String with the modifiers public final.
console is an instance of MinecraftServer with the modifiers protected final.
This is the error I’m getting (on the second last line of setMOTD):
2012-07-22 22:16:31 [SEVERE] java.lang.IllegalArgumentException: Can not set final net.minecraft.server.MinecraftServer field org.bukkit.craftbukkit.CraftServer.console to java.lang.Class
Solved by fetching the bukkit instance which extends CraftServer