Created
July 31, 2016 07:09
-
-
Save sham1/adc411d265d5fb38096238c996251aa3 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
import java.lang.invoke.MethodHandles; | |
import java.lang.invoke.MethodHandle; | |
import java.lang.invoke.MethodHandles.Lookup; | |
public class MethodHandleExample { | |
private static final MethodHandle barGetter; | |
private static final MethodHandle barSetter; | |
static { | |
Field barField = null; | |
try { | |
barField = FooClass.class.getDeclaredField("bar"); | |
barField.setAccessible(true); // Dunno if needed, but might as well | |
barGetter = MethodHandles.lookup().unreflectGetter(barField); | |
barSetter = MethodHandles.lookup().unreflectSetter(barField); | |
} catch (Exception ex) { | |
throw new RuntimeException(ex); | |
} | |
} | |
public static void setBar(FooClass foo, Bar bar) { | |
barSetter.invokeExact(foo, bar); | |
} | |
public static Bar getBar(FooClass foo) { | |
return barGetter.invokeExact(foo); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment