I\'m writing some code that calls Field.set and Field.get many many thousands of times. Obviously this is very slow because of the reflection.
I want to
There's a catch 22 for MethodHandles in JDK 7 and 8 (I haven't tested JDK 9 or higher yet): A MethodHandle is fast (as fast as direct access) if it is in a static field. Otherwise they are as slow as reflection. If your framework reflects over n getter or setters, where is n is unknown at compile time, then MethodHandles are probably useless to you.
I wrote an article that benchmarked all the different approaches to speed up reflection.
Use LambdaMetafactory (or more exotic approaches such as code generation) to speed up calling getters and setters. Here's the gist for a getter (for a setter use a BiConsumer):
public final class MyAccessor {
private final Function getterFunction;
public MyAccessor() {
MethodHandles.Lookup lookup = MethodHandles.lookup();
CallSite site = LambdaMetafactory.metafactory(lookup,
"apply",
MethodType.methodType(Function.class),
MethodType.methodType(Object.class, Object.class),
lookup.findVirtual(Person.class, "getName", MethodType.methodType(String.class)),
MethodType.methodType(String.class, Person.class));
getterFunction = (Function) site.getTarget().invokeExact();
}
public Object executeGetter(Object bean) {
return getterFunction.apply(bean);
}
}