import java.lang.reflect.Method; public class ReflectionSpeedTest { public static void main(String[] args) { int times = 100000; long simpleCallTime = simpleCall(times); long reflectionCallTime = reflectionCall(times); System.out.println("number of calls: " + times); System.out.println("simple call time: " + simpleCallTime); System.out.println("reflection call time: " + reflectionCallTime); } private static long simpleCall(int times) { ReflectionSpeedTest worker = new ReflectionSpeedTest(); long time = System.currentTimeMillis(); for (int i = 0; i < times; i++) { worker.doWork(); } return System.currentTimeMillis() - time; } private static long reflectionCall(int times) { try { Class workerClass = Class.forName("ReflectionSpeedTest"); Object workerInstance = workerClass.newInstance(); Method method = workerClass.getMethod("doWork", null); long time = System.currentTimeMillis(); for (int i = 0; i < times; i++) { method.invoke(workerInstance, null); } return System.currentTimeMillis() - time; } catch (Exception e) { throw new RuntimeException(e); } } public void doWork() { int i = 5 * 6; } }