Invoking Methods


Baseball bbObj = new Baseball(); Class c = Baseball.class; Class[] paramTypes =    new Class[] {int.class, int.class}; Method calcMeth =    c.getMethod("calcBatAvg", paramTypes); Object[] args =    new Object[] {new Integer(30), new Integer(100)}; Float result = (Float) calcMeth.invoke(bbObj, args);



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:

Get a Method object associated with the calcBatAvg() method from the Class object that represents the Baseball class.

Invoke the calcBatAvg() method using the invoke() method on the Method object. The invoke() method takes two parameters: The first is an object whose class declares or inherits the method, and the second is an array of parameter values to be passed to the invoked method. If the method is a static method, the first parameter will be ignored and might be null. If the method does not take any parameters, the argument array might be of zero length, or null.

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.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net