Skip to content

Instantly share code, notes, and snippets.

@rbrick
Created November 3, 2014 02:59
Show Gist options
  • Save rbrick/fe22df8cc44a00cfbe13 to your computer and use it in GitHub Desktop.
Save rbrick/fe22df8cc44a00cfbe13 to your computer and use it in GitHub Desktop.
Reflection Utilities
/**
* Created by Ryan on 11/2/2014
* <p/>
* Project: Phenomenon
*
* About: Various reflection utilities created by @rbrick(Ryan)
*/
public class Reflection {
private static String VERSION = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
private static String NMS = "net.minecraft.server";
private static String OBC = "org.bukkit.craftbukkit";
public static Class<?> getCraftBukkitClass(String className) {
try {
return Class.forName(OBC + "." + VERSION + "." + className);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static Class<?> getMinecraftClass(String className) {
try {
return Class.forName(NMS + "." + VERSION + "." + className);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// For utility use solely.
private static Class<?> getPacketClass() {
return getMinecraftClass("Packet");
}
public static Object getHandle(Object entity) {
try {
Method method = entity.getClass().getDeclaredMethod("getHandle");
return method.invoke(entity);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Object getHandle(Entity entity) {
try {
Method method = entity.getClass().getMethod("getHandle");
return method.invoke(entity);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void sendPacket(Player player, Object packet) {
try {
Object entity_player = getHandle(player);
Field player_connection = entity_player.getClass().getField("playerConnection");
player_connection.setAccessible(true);
Object initiatedConnection = player_connection.get(entity_player);
Method sendPacket = initiatedConnection.getClass().getMethod("sendPacket", getPacketClass());
sendPacket.invoke(initiatedConnection, packet);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment