Skip to content

Instantly share code, notes, and snippets.

@noobmobile
Last active January 4, 2020 23:13
Show Gist options
  • Save noobmobile/b8534ec44d66e422ddd7090741d0a237 to your computer and use it in GitHub Desktop.
Save noobmobile/b8534ec44d66e422ddd7090741d0a237 to your computer and use it in GitHub Desktop.
package com.dont.testes.utils;
import org.bukkit.Bukkit;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
public class Reflections {
public enum Package {
NMS("net.minecraft.server.<version>."), CRAFTBUKKIT("org.bukkit.craftbukkit.<version>.");
private String packageName;
Package(String packageName) {
this.packageName = packageName;
}
public Class getClass(String name){
return Reflections.getClass(packageName.replace("<version>", version) + name);
}
}
private static final String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
private static final HashMap<String, Object> CACHE = new HashMap<>();
private static Class getClass(String name){
if (!CACHE.containsKey(name)){
try {
CACHE.put(name,Class.forName(name));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return (Class) CACHE.get(name);
}
public static Method getMethod(Class clazz, String method, Class<?>... parameterTypes){
if (!CACHE.containsKey(clazz.getName() + "." + method)){
try {
CACHE.put(clazz.getName() + "." + method, clazz.getDeclaredMethod(method, parameterTypes));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
return (Method) CACHE.get(clazz.getName() + "." + method);
}
public static Constructor getConstructor(Class clazz, Class... params){
try {
return clazz.getDeclaredConstructor(params);
} catch (NoSuchMethodException e) {
e.printStackTrace();
return null;
}
}
public static Object construct(Constructor constructor, Object... params){
try {
return constructor.newInstance(params);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
public static Object invokeMethod(Method method, Object object, Object... args){
try {
return method.invoke(object, args);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
public static Object invokeField(Field field, Object object){
try {
return field.get(object);
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
public static Field getField(Class clazz,String field){
if (!CACHE.containsKey(clazz.getName() + "." + field)){
try {
CACHE.put(clazz.getName() + "." + field, clazz.getDeclaredField(field));
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
return (Field) CACHE.get(clazz.getName() + "." + field);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment