Skip to content

Instantly share code, notes, and snippets.

@elliptic-shiho
Created March 14, 2015 05:38
Show Gist options
  • Save elliptic-shiho/1e23c7ba039ec9abdf66 to your computer and use it in GitHub Desktop.
Save elliptic-shiho/1e23c7ba039ec9abdf66 to your computer and use it in GitHub Desktop.
Curry
package xyz.elliptic_shiho.Curry;
public class CMain {
public static void main(String...args) {
Curry.curry(CMain.class, "foo", new Class[]{double.class, int.class}, 1, 20).invoke(null, 1.5);
}
public int add(int a, int b) {
return a + b;
}
public static void foo(double A, int b) {
System.out.println(A + b);
}
}
package xyz.elliptic_shiho.Curry;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
public class Curry {
public static Invokable curry(Class<?> par1Class, String par2Method, Class<?>[] par3ParamTypes, int par4ParamOrd, Object par5param) {
try {
if(par3ParamTypes.length <= par4ParamOrd) {
throw new RuntimeException("Error: par3ParamType.length <= par4ParamOrd");
}
final Method m = par1Class.getMethod(par2Method, par3ParamTypes);
return new Invokable() {
@Override
public Object invoke(Object instance, Object... objects) {
Object[] arg = new Object[par3ParamTypes.length];
Deque<Object> queue = new LinkedList<>(Arrays.asList(objects));
for(int i = 0; i < arg.length; i++) {
if(i == par4ParamOrd) {
arg[i] = par5param;
} else {
arg[i] = queue.pop();
}
}
try {
return m.invoke(instance, arg);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
};
} catch (NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
}
}
package xyz.elliptic_shiho.Curry;
public interface Invokable {
public Object invoke(Object instance, Object... objects);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment