Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 585
Stephan Avatar asked Jan 01 '26 04:01

Stephan


1 Answers

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.

like image 72
Reverend Gonzo Avatar answered Jan 02 '26 19:01

Reverend Gonzo