dimanche 27 octobre 2019

Given the method name and an array of objects how can I find the best match overload with Java Reflections

I've been playing around with reflections in Java and have come across a fairly difficult problem to solve.

Given just the name of a method and an array of Objects how can I find the best match overload of that method?

I am aware that I can quickly rule out many overloads in most cases by just checking if the length of the parameter list matches the length of my array.
Next I can check if I can cast all objects of the array into the expected types with relfections (I forgot the exact method name, but it can be done).

However I run into an issue when multiple methods match with that procedure.

Let's say I have these two methods:

public void doStuff(Collection<?> data) {
    // Do stuff
}

public void doStuff(List<?> data) {
    // Do stuff
}

If I were to pass have an array with a single Set (or subtype of it) object then I can easily rule out the second overload. Because Sets are not a subinterface/subtype of List.

Having an ArrayList object now makes it hard, because an ArrayList is both a Collection and a List.
I know if I were to use regular code the compiler would certainly use the second method because it's a better/more close match. But how can I do a similar thing with reflections?

I'm interested in all kinds of solutions, although I'd prefer solutions that use the JRE libraries, standalone classes or small (single purpose) libraries.
Also, I'm specifically using Java 8, though if more up to date versions of the language provide simpler methods to do just that, they are still very welcome as answers.





Aucun commentaire:

Enregistrer un commentaire