Created
June 12, 2016 18:08
-
-
Save anonymous/7cabe890a28547dad0401dc7883cc4a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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