Skip to content

Instantly share code, notes, and snippets.

@FarisR99
Last active August 29, 2015 14:05
Show Gist options
  • Save FarisR99/044e15daf41b8049e783 to your computer and use it in GitHub Desktop.
Save FarisR99/044e15daf41b8049e783 to your computer and use it in GitHub Desktop.
Set a beacon active.
public static class ReflectionUtils {
public static String getVersion() {
return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
}
public static Class<?> getNMSClass(String name) {
Class<?> clazz = null;
try {
clazz = Class.forName("net.minecraft.server." + getVersion() + "." + name);
} catch (ClassNotFoundException e) { e.printStackTrace(); }
return clazz;
}
public static Field getField(Class<?> clazz, String name) {
Field field = null;
try {
field = clazz.getField(name);
} catch (Exception e) { }
if (field == null) {
try {
field = clazz.getDeclaredField(name);
} catch (Exception e) { }
}
if (field != null) field.setAccessible(true);
return field;
}
public static Method getMethod(Class<?> clazz, String name, Class<?>... params) {
Method method = null;
try {
method = clazz.getMethod(name, params);
} catch (Exception e) {}
if (method == null) {
try {
method = clazz.getMethod(name, params);
} catch (Exception e) {}
}
if (method != null) method.setAccessible(true);
return method;
}
}
public static class WorldUtils {
public static void setBeaconActive(Block block, boolean state) {
if (block == null || !(block.getState() instanceof Beacon)) return;
try {
Class beaconClass = ReflectionUtils.getNMSClass("TileEntityBeacon");
Class worldClass = block.getWorld().getClass();
Object nmsWorld = ReflectionUtils.getMethod(worldClass, "getHandle").invoke(block.getWorld());
Method tileEntityMethod = ReflectionUtils.getMethod(nmsWorld.getClass(), "getTileEntityAt", Integer.class, Integer.class, Integer.class);
if (tileEntityMethod != null) {
Object beacon = tileEntityMethod.invoke(nmsWorld, block.getX(), block.getY(), block.getZ());
Field active;
try {
ReflectionUtils.getField(beaconClass, "i").set(beacon, state);
} catch (Exception ex) {
throw ex;
}
}
} catch (Exception ex) {
ex.printStackTrace();
block.getState().update();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment