Stephan
Stephan

Reputation: 43053

Java Reflection - Matching formal parameter list to actual parameter list

Let say I have a class Foo like this

public class Foo {
    public void setParameter(String name, Object value) {
       // ...
    }
}

I would like to get the setParameter method through reflection.

The problem is that in my code, I only know the ACTUAL parameters when I need to get this method. I have build a little method that can give me the Class array of actual parameters. Unfortunately the returned Class array from actual parameters ([String.class, String.class]) doesn't match the Class array of formal parameters ([String.class, Object.class]) and getDeclaredMethod raises exception NoSuchMethodException.

Do you know of any library or code snippet that can help match the method ?

Upvotes: 3

Views: 1019

Answers (2)

Reverend Gonzo
Reverend Gonzo

Reputation: 40851

You'll probably need to be a little smarter about finding which method to call. One option is to iterate through each method from getDeclaredMethods(), first checking the name of the method to see if that's the one you want to call, then checking if the number of actual parameters matches the number of formal parameters, and lastly, if both of those are true, iterating through its actual parameters and checking if the parameter class is assignable from your formal parameter class.

One problem, however, is what happens if you have the methods:

public void setParameter(String name, Object value);
public void setParameter(String name, String value);

as both will match that test.

I don't know of any library of the top of my head that can handle that in a lightweight way. Though most dependency-injection frameworks (Spring, Guice) would have some support for it for their needs, and it may be worth looking into how they do things.

Jon Skeet's answer here has an example of what I'm explaining.

Upvotes: 4

Michael Borgwardt
Michael Borgwardt

Reputation: 346417

I'd simply use getDeclaredMethods() to get all maethods and then do the matching in your code, based on method name, parameter count and finally Class.isAssignableFrom() to check whether the parameters' types match the signature. That leaves cases where overloaded methods' signatures differ in types that can be compatible with the same concrete type (interfaces or super/subclasses). You have to decide whether your code has to support such corner cases.

Upvotes: 2

Related Questions