|
|
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
Classobject that corresponds to the object whose method you want to invoke. See the section Retrieving Class Objects for more information.- Create a
Methodobject by invoking
getMethodon theClassobject. ThegetMethodmethod has two arguments: aStringcontaining the method name, and an array ofClassobjects. Each element in the array corresponds to a parameter of the method you want to invoke. For more information on retrievingMethodobjects, see the section Obtaining Method Information- Invoke the method by calling
invoke. Theinvokemethod 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
Methodobject for theString.concatmethod and then usesinvoketo concatenate twoStringobjects.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-2004 Sun Microsystems, Inc. All rights reserved.