Java Reference
In-Depth Information
What if we need to find a method? The simplest way is to use the methods getMethod() and
invoke() . But this is not altogether trivial. Suppose that somebody gives us a reference to an
object. We don't know its class but have been told that it should have this method:
public void work(String s) { }
We wish to invoke work() . To find the method, we must make an array of Class objects,
one per item in the parameter list. So, in this case, we make an array containing only a refer-
ence to the class object for String . Because we know the name of the class at compile time,
we'll use the shorter invocation String.class instead of Class.forName() . This, plus the
name of the method as a string, gets us entry into the getMethod() method of the Class ob-
ject. If this succeeds, we have a Method object. But guess what? In order to invoke the meth-
od, we have to construct yet another array, this time an array of Object references actually
containing the data to be passed to the invocation. We also, of course, need an instance of the
class in whose context the method is to be run. For this demonstration class, we need to pass
only a single string, because our array consists only of the string. Example 23-3 is the code
that finds the method and invokes it.
Example 23-3. GetAndInvokeMethod.java
/**
* Get a given method, and invoke it.
* @author Ian F. Darwin, http://www.darwinsys.com/
*/
public
public class
class GetAndInvokeMethod
GetAndInvokeMethod {
/** This class is just here to give us something to work on,
* with a println() call that will prove we got into it.
*/
static
static class
class X {
public
public void
int i , String s ) {
System . out . printf ( "Called: i=%d, s=%s%n" , i , s );
void work ( int
}
// The main code does not use this overload.
public
public void
int i ) {
System . out . println ( "Unexpected call!" );
void work ( int
}
}
public
public static
static void
void main ( String [] argv ) {
try
try {
Class <?> clX = X . class ; // or Class.forName("X");
Search WWH ::




Custom Search