Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection parameter type matching, how-to handle interfaces instead classes

Given a class Something with a constructor public Something(List<String> l), I would like to use klass.getConstructor(parameterTypes) where parameterTypes[0] is the class java.util.ArrayList (because I need to "match" a given specific instance) and not the interface java.util.List.

This doesn't work (NoSuchMethodException), because Java Reflection appears to need an EXACT type class match. What is the best way around this?

like image 277
vorburger Avatar asked Jul 21 '26 12:07

vorburger


1 Answers

Might be overkill, and admittedly could pick up too many constructors:

Constructor[] constructors = klass.getConstructors();
for(Constructor constructor:constructors) {
      Class<?>[] params = constructor.getParameterTypes();
      if(params.length == 1 && params[0].isAssignableFrom(ArrayList.class) {
          //Yep could be the one you want.
      }
}
like image 175
Charlie Avatar answered Jul 23 '26 02:07

Charlie