Skip to content

Instantly share code, notes, and snippets.

@jamesbirtles
Created May 7, 2015 00:24
Show Gist options
  • Save jamesbirtles/76d4e367ac527e5e161f to your computer and use it in GitHub Desktop.
Save jamesbirtles/76d4e367ac527e5e161f to your computer and use it in GitHub Desktop.
package unwrittenfun.sponge.lunge.lua.tables;
import org.luaj.vm2.LuaTable;
import unwrittenfun.sponge.lunge.lua.functions.IValidFunction;
import unwrittenfun.sponge.lunge.lua.functions.LuaGenericFunction;
import java.lang.reflect.Method;
import java.util.*;
public class LuaJavaObject extends LuaTable {
public static Map<Class<?>, Map<String, List<IValidFunction>>> overrideMap = new HashMap<Class<?>, Map<String, List<IValidFunction>>>();
public Object object;
public LuaJavaObject(Object object) {
this.object = object;
Method[] methods = object.getClass().getMethods();
Map<String, List<Method>> methodMap = new HashMap<String, List<Method>>();
for (Method method : methods) {
if (!methodMap.containsKey(method.getName())) {
methodMap.put(method.getName(), new ArrayList<Method>());
}
methodMap.get(method.getName()).add(method);
}
Map<String, List<IValidFunction>> overrides = new HashMap<String, List<IValidFunction>>();
for (Class<?> classType : overrideMap.keySet()) {
if (classType.isInstance(object)) {
Map<String, List<IValidFunction>> functionMap = overrideMap.get(classType);
for (String functionName : functionMap.keySet()) {
if (!overrides.containsKey(functionName)) {
overrides.put(functionName, new ArrayList<IValidFunction>());
}
overrides.get(functionName).addAll(functionMap.get(functionName));
}
}
}
for (String methodName : methodMap.keySet()) {
set(methodName, new LuaGenericFunction(object, methodMap.get(methodName), overrides.get(methodName)));
}
}
public static void addOverride(Class<?> classType, String functionName, IValidFunction... overrides) {
if (!overrideMap.containsKey(classType)) {
overrideMap.put(classType, new HashMap<String, List<IValidFunction>>());
}
Map<String, List<IValidFunction>> functionMap = overrideMap.get(classType);
if (!functionMap.containsKey(functionName)) {
functionMap.put(functionName, new ArrayList<IValidFunction>());
}
List<IValidFunction> functions = functionMap.get(functionName);
functions.addAll(Arrays.asList(overrides));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment