Progress Checker
Note: This example illustrates a major drawback
of using Reflection in our programming. The debate of time-efficiency vs. capability
has evolved into a science. I will perform a very cursory analysis
by measuring the cost of using certain Java Reflection functions (method invoking,
in this case) and comparing it with simply using direct method calling.
PCClassCreator.java is a hybrid of ProgressChecker.java
and ClassCreator.java (from the
previous example). This example uses the method and the invoke functionality implemented
by the Reflection API and contrasts it with running the same code without Reflection.
It also takes the principles of ProgressChecker and uses an average-time computation
for both method calls (Reflection and direct) and prints the values of the comparison.
The following were the average of the results I obtained after several tests:
Time: 500.0 ms for calling Add.main
using Reflection.
Time: 70.0 ms for calling 'add' directly.
Average Time:
0.03333333333333333 ms for Reflection.
0.004666666666666667 ms for Normal method call to add
Note: mult in PCClassCreator and main in Add have the exact same code, so in
general the disparity in time is caused primarily by the introspection Reflection
implements.
As is readily apparent, using Reflection to implement the method invoker is slower
by a factor of 6 or 7.
Source Code (PCClassCreator.java)