Skip to content

Instantly share code, notes, and snippets.

Created June 12, 2016 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7cabe890a28547dad0401dc7883cc4a7 to your computer and use it in GitHub Desktop.
Save anonymous/7cabe890a28547dad0401dc7883cc4a7 to your computer and use it in GitHub Desktop.
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