Skip to content

Instantly share code, notes, and snippets.

@sham1
Created July 31, 2016 07:09
Show Gist options
  • Save sham1/adc411d265d5fb38096238c996251aa3 to your computer and use it in GitHub Desktop.
Save sham1/adc411d265d5fb38096238c996251aa3 to your computer and use it in GitHub Desktop.
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