Re: getMethod() works and works not
"Alexander Burger" <abu@software-lab.de> wrote in message
news:icripp$b4k$3@online.de...
Hi Aeris,
class U
class V extends U
class A
void bar(U u)
class B extends A
B.getMethod("bar", U.class) returns the A.bar(U) by inheritance
But B.getMethod("bar", V.class) and A.getMethod("bar", V.class) fail,
because there is no B.bar(V) or A.bar(V)
I understand. But in my case I have no class at all. Just an object and
a method name.
From the reference I expect that getMethod() is able by searching up the
class hierarchy to locate a method matching the signature (i.e. the
array of classes passed in the second argument to getMethod()). Otherwise
it would be pretty useless.
The precise search used by the compiler to find a matching method is
documentedn the JLS at
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.
As you'll see it's*very* complicated, and getMethod() doesn't even try to
replicate it. Rather, getMethod() assumes you've given it the genuine
parameter types (not subclasses thereof), and looks up the hierarchy for an
exact match.
You could probably get what you want with a small subset of the logic in
15.12, e.g.:
0. Given the object O you want to call the method on, the method name M,
and a list of arguments A:
1. Call O.getClass().getMethods() to find all the public methods callable on
O.
2. Reject the ones not named M
3. Reject the ones with the wrong number of arguments. (Be careful here if
you're going to support variable-argument methods)
4. If more than one remains, check which have compatible argument types
5. If exactly one remains, call it. Otherwise throw an exception.