Skip to content

Instantly share code, notes, and snippets.

@keir-nellyer
Created December 2, 2013 20:39
Show Gist options
  • Save keir-nellyer/7758525 to your computer and use it in GitHub Desktop.
Save keir-nellyer/7758525 to your computer and use it in GitHub Desktop.
Update 1.7.2
package com.iKeirNez.CastleDefence.slave.utilities;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by iKeirNez on 10/11/13.
*/
public class ReflectionHelper {
public static void sendPacket(Player p, Object packet){
try {
Object nmsPlayer = getHandle(p);
Field con_field = nmsPlayer.getClass().getField("playerConnection");
Object con = con_field.get(nmsPlayer);
Method packet_method = getMethod(con.getClass(), "sendPacket");
packet_method.invoke(con, packet);
} catch (SecurityException | NoSuchFieldException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
e.printStackTrace();
}
}
public static Class<?> getNMSClass(String className){
String name = Bukkit.getServer().getClass().getPackage().getName();
String version = name.substring(name.lastIndexOf('.') + 1)+".";
String finalClassName = "net.minecraft.server." + version + className;
Class<?> c = null;
try {
c = Class.forName(finalClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return c;
}
public static Object getHandle(Entity entity){
Object nms_entity = null;
Method entity_getHandle = getMethod(entity.getClass(), "getHandle");
try {
nms_entity = entity_getHandle.invoke(entity);
} catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return nms_entity;
}
public static Field getField(Class<?> cl, String field_name){
try {
Field field = cl.getDeclaredField(field_name);
return field;
} catch (NoSuchFieldException | SecurityException e){
e.printStackTrace();
}
return null;
}
public static Method getMethodNoArgs(Class<?> cl, String method){
for (Method method1 : cl.getMethods()){
if (method1.getName().equals(method) && method1.getParameterTypes().length == 0){
return method1;
}
}
return null;
}
public static Method getMethod(Class<?> cl, String method){
for (Method method1 : cl.getMethods()){
if (method1.getName().equals(method)){
return method1;
}
}
return null;
}
public static Method getMethod(Class<?> cl, String method, Class<?>[] args) {
try {
return cl.getMethod(method, args);
} catch (NoSuchMethodException e) {
e.printStackTrace();
return null;
}
}
public static boolean classListEqual(Class<?>[] l1, Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment