Main demo method.
try {
final int CALL_AMOUNT = 1000000;
final ReflexiveInvocation ri = new ReflexiveInvocation();
int idx = 0;
// Call the method without using reflection.
long millis = System.currentTimeMillis();
for (idx = 0; idx < CALL_AMOUNT; idx++) {
ri.getValue();
}
System.out.println("Calling method " + CALL_AMOUNT
+ " times programatically took "
+ (System.currentTimeMillis() - millis) + " millis");
// Call while looking up the method in each iteration.
Method md = null;
millis = System.currentTimeMillis();
for (idx = 0; idx < CALL_AMOUNT; idx++) {
md = ri.getClass()
.getMethod("getValue", null);
md.invoke(ri, null);
}
System.out.println("Calling method " + CALL_AMOUNT
+ " times reflexively with lookup took "
+ (System.currentTimeMillis() - millis) + " millis");
// Call using a cache of the method.
md = ri.getClass()
.getMethod("getValue", null);
millis = System.currentTimeMillis();
for (idx = 0; idx < CALL_AMOUNT; idx++) {
md.invoke(ri, null);
}
System.out.println("Calling method " + CALL_AMOUNT
+ " times reflexively with cache took "
+ (System.currentTimeMillis() - millis) + " millis");
} catch (final NoSuchMethodException ex) {
throw new RuntimeException(ex);
} catch (final InvocationTargetException ex) {
throw new RuntimeException(ex);
} catch (final IllegalAccessException ex) {
throw new RuntimeException(ex);
}