How can I get Java reflection to find a callable f

2019-07-15 11:45发布

问题:

I have an interface ZipCodeServer which the class ZipCodeServerImpl implements.

I also have an interface ZipCodeList which the class ZipCodeListImpl implements.

One of the functions that the ZipCodeServer interface requires is

public void initialise(ZipCodeList newlist) throws RemoteException;

Now as you can imagine, this works fine when I try to pass in a ZipCodeListImpl to the initialise function.

But when I try to do it via reflection (syntax is not correct, but basically I am passing in an array of only the class ZipCodeListImpl):

aZipCodeServer.getClass().getMethod("initialise", [aZipCodeListImpl.getClass()]);

I get the error:

java.lang.NoSuchMethodException: ZipCodeServerImpl.initialise(ZipCodeListImpl)

of course because the function expects a ZipCodeList parameter.

Thing is, this code has to be generic, so I have the list of parameters and the function name, but I have to find the function itself via reflection.

回答1:

I'm not sure what you mean by generics in this case, but since the parameter type is ZipCodeList, you'll need to use the Class object for that as an argument to getMethod. If you don't have it, you can recursively traverse the class/interface hierarchy of the subclass, trying each as you go.



回答2:

Use java.beans.Expression:

new Expression(server, "initialise", new Object[] { list }).execute();

This should handle subtype relationships between formal parameters and actual arguments, as well as primitive-vs.-wrapper boxing/unboxing. It won't handle primitive widening though: see this bug report.