The simple solution is to write a more realistic benchmark which does something almost useful so it will not be optimised away.
There are a number of trick to confuse the JIT, but these are unlikely to help you.
Here is example of a benchmark where the method is called via reflection, MethodHandle and compiled to nothing.
import java.lang.invoke.*;
import java.lang.reflect.*;
public class Main {
public static void main(String... args) throws Throwable {
for (int j = 0; j < 5; j++) {
testViaReflection();
testViaMethodHandle();
testWithoutReflection();
}
}
private static void testViaReflection() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Method nothing = Main.class.getDeclaredMethod("nothing");
int runs = 10000000; // triggers a warmup.
long start = System.nanoTime();
Object[] args = new Object[0];
for (int i = 0; i < runs; i++)
nothing.invoke(null, args);
long time = System.nanoTime() - start;
System.out.printf("A call to %s took an average of %.1f ns using reflection%n", nothing.getName(), 1.0 * time / runs);
}
private static void testViaMethodHandle() throws Throwable {
MethodHandle nothing = MethodHandles.lookup().unreflect(Main.class.getDeclaredMethod("nothing"));
int runs = 10000000; // triggers a warmup.
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
nothing.invokeExact();
}
long time = System.nanoTime() - start;
System.out.printf("A call to %s took an average of %.1f ns using MethodHandle%n", "nothing", 1.0 * time / runs);
}
private static void testWithoutReflection() {
int runs = 10000000; // triggers a warmup.
long start = System.nanoTime();
for (int i = 0; i < runs; i++)
nothing();
long time = System.nanoTime() - start;
System.out.printf("A call to %s took an average of %.1f ns without reflection%n", "nothing", 1.0 * time / runs);
}
public static void nothing() {
// does nothing.
}
}
prints
A call to nothing took an average of 6.6 ns using reflection
A call to nothing took an average of 10.7 ns using MethodHandle
A call to nothing took an average of 0.4 ns without reflection
A call to nothing took an average of 4.5 ns using reflection
A call to nothing took an average of 9.1 ns using MethodHandle
A call to nothing took an average of 0.0 ns without reflection
A call to nothing took an average of 4.3 ns using reflection
A call to nothing took an average of 8.8 ns using MethodHandle
A call to nothing took an average of 0.0 ns without reflection
A call to nothing took an average of 5.4 ns using reflection
A call to nothing took an average of 13.2 ns using MethodHandle
A call to nothing took an average of 0.0 ns without reflection
A call to nothing took an average of 4.9 ns using reflection
A call to nothing took an average of 8.7 ns using MethodHandle
A call to nothing took an average of 0.0 ns without reflection
I had assumed MethodHandles to be faster than reflection but it doesn't appear so.