Java Reference
In-Depth Information
and the class has yet to be initialized, you might get an Ex-
ceptionInInitializerError . If the method throws an exception,
an InvocationTargetException is thrown whose cause is that ex-
ception.
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 , return-
ing 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;
 
Search WWH ::




Custom Search