Skip to content

Instantly share code, notes, and snippets.

@ejemba
Created March 20, 2017 15:58
Show Gist options
  • Save ejemba/9a1a1b2d04c31edfcf8230b9d0d2d19c to your computer and use it in GitHub Desktop.
Save ejemba/9a1a1b2d04c31edfcf8230b9d0d2d19c to your computer and use it in GitHub Desktop.
How to get Method Reference for all methods in a class (Java)?
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.DoubleUnaryOperator;
class Test {
public static double op0(double a) {
return a;
}
public static double op1(double a) {
return a;
}
public static double op2(double a) {
return a;
}
public static double op3(double a) {
return a;
}
public static double op4(double a) {
return a;
}
static final Map<String, DoubleUnaryOperator> OPS;
static {
HashMap<String, DoubleUnaryOperator> map = new HashMap<>();
MethodType type = MethodType.methodType(double.class, double.class);
MethodType inT = MethodType.methodType(DoubleUnaryOperator.class);
MethodHandles.Lookup l = MethodHandles.lookup();
for (Method m : Test.class.getDeclaredMethods())
try {
if (!Modifier.isStatic(m.getModifiers()))
continue;
MethodHandle mh = l.unreflect(m);
if (!mh.type().equals(type))
continue;
map.put(m.getName(), (DoubleUnaryOperator) LambdaMetafactory.metafactory(
l, "applyAsDouble", inT, type, mh, type).getTarget().invokeExact());
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
OPS = Collections.unmodifiableMap(map);
}
public static void main(String args[]) {
OPS.forEach((name, op) -> System.out.println(name + '(' + 42 + ") => " + op.applyAsDouble(42)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment