Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Suppose that you are writing a debugger that allows the user to select and then invoke methods during a debugging session. Since you don't know at compile time which methods the user will invoke, you cannot hardcode the method name in your source code. Instead, you must follow these steps:
- Create a
Class
object that corresponds to the object whose method you want to invoke. See the section Retrieving Class Objects for more information.- Create a
Method
object by invokinggetMethod
on theClass
object. ThegetMethod
method has two arguments: aString
containing the method name, and an array ofClass
objects. Each element in the array corresponds to a parameter of the method you want to invoke. For more information on retrievingMethod
objects, see the section Obtaining Method Information- Invoke the method by calling
invoke
. Theinvoke
method has two arguments: an array of argument values to be passed to the invoked method, and an object whose class declares or inherits the method.The sample program that follows shows you how to invoke a method dynamically. The program retrieves the
Method
object for theString.concat
method and then usesinvoke
to concatenate twoString
objects.The output of the preceding program is:import java.lang.reflect.*; class SampleInvoke { public static void main(String[] args) { String firstWord = "Hello "; String secondWord = "everybody."; String bothWords = append(firstWord, secondWord); System.out.println(bothWords); } public static String append(String firstWord, String secondWord) { String result = null; Class c = String.class; Class[] parameterTypes = new Class[] {String.class}; Method concatMethod; Object[] arguments = new Object[] {secondWord}; try { concatMethod = c.getMethod("concat", parameterTypes); result = (String) concatMethod.invoke(firstWord, arguments); } catch (NoSuchMethodException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } return result; } }Hello everybody.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.