The reflection API allows you to dynamically invoke methods even if the method name that you want to invoke is not known at compile time. In order to invoke a method, you must first get a Method object for the method that you want to invoke. See the phrase "Discovering Method Information" earlier in this chapter for more information about getting Method objects from a class. In this phrase, we are trying to invoke a method that calculates a baseball batting average. The method is called calcBatAvg(), and it takes two integer parameters, a batter's hit count, and at-bat count. The method returns a batting average as a Float object. We invoke the method calcBatAvg() using the following steps:
In the case of our phrase, we pass an instance of the Baseball object as the first parameter to the invoke() method and an object array containing two wrapped integer values as our second parameter. The return value returned from the invoke () method will be the value returned from the method being invoked, in this case the calcBatAvg() return value. If the method returns a primitive, the value will first be wrapped in as an object and returned as an object. If the method has a return type of void, a null will be returned. The calcBatAvg() method returns a Float value, so we cast the returned object to be a Float object. An example of where this technique would be useful is in the implementation of a debugger that allows a user to select a method and invoke it. Since the method being selected is not known until runtime, this reflective technique would be used to invoke that method. |