Skip to content

Instantly share code, notes, and snippets.

Created Jun 12, 2016
Embed
What would you like to do?
package fr.umlv.constantify;
import static java.lang.invoke.MethodHandles.constant;
import static java.lang.invoke.MethodHandles.dropArguments;
import static java.lang.invoke.MethodType.methodType;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
public class ConstantifyCS extends MutableCallSite {
private static final MethodHandle FALLBACK;
static {
try {
FALLBACK = MethodHandles.lookup().findVirtual(ConstantifyCS.class, "fallback",
methodType(Object.class, Object.class));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
}
}
private ConstantifyCS(MethodType type) {
super(type);
setTarget(FALLBACK.bindTo(this).asType(type));
}
private Object fallback(Object value) {
Class<?> clazz = type().parameterType(0);
setTarget(dropArguments(constant(clazz, value), 0, clazz));
return value;
}
public static MethodHandle constantify(Class<?> type) {
return new ConstantifyCS(methodType(type, type)).dynamicInvoker();
}
}
import java.lang.invoke.MethodHandle;
import fr.umlv.constantify.ConstantifyCS;
public class Main {
private static final MethodHandle CST = ConstantifyCS.constantify(int.class);
static int f(int i) {
try {
return (int) CST.invokeExact(i);
} catch (Throwable e) {
throw new AssertionError(e);
}
}
public static void main(String[] args) {
System.out.println(f(2));
System.out.println(f(2));
System.out.println(f(3));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment