THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

The most interesting use of a Method object is to reflectively invoke it:


public Objectinvoke(Object onThis, Object... args)tHRows
IllegalAccessException, IllegalArgumentException,
InvocationTargetException

Invokes the method defined by this Method object on the object onThis,
setting the parameters of the method from the values in args. For non-static
methods the actual type of onThis determines the method implementation
that is invoked. For static methods onThis is ignored and is traditionally
null. The number of args values must equal the number of parameters for
the method, and the types of those values must all be assignable to those of
the method. Otherwise you will get an IllegalArgumentException.
Note that for a varargs method the last parameter is an array that you must fill
with the actual "variable" arguments you want to pass. If you attempt to
invoke a method to which you do not have access, an
IllegalAccessException is thrown. If this method is not a method of
the onThis object, an IllegalArgumentException is thrown. If
onThis is null and the method is not static, a
NullPointerException is thrown. If this Method object represents a
static method and the class has yet to be initialized, you might get an
ExceptionInInitializerError. If the method throws an exception,
an InvocationTargetException is thrown whose cause is that
exception.

When you use invoke, you can either pass primitive types directly, or use wrappers of suitable types. The
type represented by a wrapper must be assignable to the declared parameter type. You can use a Long,
Float, or Double to wrap a double argument, but you cannot use a Double to wrap a long or float
argument because a double is not assignable to a long or a float. The Object returned by invoke is
handled as with Field.get, returning primitive types as their wrapper classes. If the method is declared
void, invoke returns null.


Simply put, you can use invoke only to invoke a method with the same types and values that would be legal
in the language. The invocation


return str.indexOf(".", 8);


can be written using reflection in the following way:


Throwable failure;
try {
Method indexM = String.class.
getMethod("indexOf", String.class, int.class);
return (Integer) indexM.invoke(str, ".", 8);
} catch (NoSuchMethodException e) {
failure = e;
} catch (InvocationTargetException e) {
failure = e.getCause();
} catch (IllegalAccessException e) {
failure = e;
}
throw failure;

Free download pdf