|
| 1 | +package benchmark; |
| 2 | + |
| 3 | +import org.openjdk.jmh.annotations.*; |
| 4 | +import java.lang.invoke.*; |
| 5 | +import java.lang.reflect.Method; |
| 6 | +import java.util.function.Function; |
| 7 | + |
| 8 | +public class ReferenceReflectiveAccessBenchmark extends AbstractReflectiveAccessBenchmark { |
| 9 | + private Method method; |
| 10 | + private MethodHandle methodHandle; |
| 11 | + private Function<SomeSource, ?> lambdaMetafactoryFunction; |
| 12 | + |
| 13 | + @Setup |
| 14 | + public void setup() { |
| 15 | + try { |
| 16 | + final MethodHandles.Lookup lookup = MethodHandles.lookup(); |
| 17 | + |
| 18 | + method = source.getClass().getDeclaredMethod("getObject"); |
| 19 | + |
| 20 | + methodHandle = lookup.unreflect(method); |
| 21 | + |
| 22 | + lambdaMetafactoryFunction = (Function<SomeSource, ?>) LambdaMetafactory |
| 23 | + .metafactory(lookup, "apply", MethodType.methodType(Function.class), |
| 24 | + MethodType.methodType(Object.class, Object.class), methodHandle, methodHandle.type()) |
| 25 | + .getTarget().invokeExact(); |
| 26 | + } catch (final Throwable t) { |
| 27 | + throw new ExceptionInInitializerError(t); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + @Benchmark |
| 32 | + public Object direct() throws Throwable { |
| 33 | + return source.getObject(); |
| 34 | + } |
| 35 | + |
| 36 | + @Benchmark |
| 37 | + public Object reflection() throws ReflectiveOperationException { |
| 38 | + return method.invoke(source); |
| 39 | + } |
| 40 | + |
| 41 | + @Benchmark |
| 42 | + public Object methodHandle() throws Throwable { |
| 43 | + return methodHandle.invoke(source); |
| 44 | + } |
| 45 | + |
| 46 | + @Benchmark |
| 47 | + public Object lambdaMetafactory() { |
| 48 | + return lambdaMetafactoryFunction.apply(source); |
| 49 | + } |
| 50 | +} |
0 commit comments