One way to handle this is to load this list of methods at runtime into Map , and then use Map for each call. That is, something like this (where this code is simplified and skips error checking):
Map<? extends Object, Method> map; Method[] methods = Setters.class.getMethods(); for (Method method : methods) { if (method.getName().equals("setCellValue")) { map.put(method.getParameterTypes()[0], method); } }
then when you want to call this, find the method in the Map type by argument and use this instance.
To show this, again with a simplified, but this time complete code. Please note that in order to be completely general, the code becomes a little more complex, as shown below. If you don’t need to worry about primitives (which depend on your use), or if you don’t need to worry about interfaces or superclasses, you can simplify the example below.
In addition, if you can guarantee that there are no matches in the interfaces or superclasses in the arguments that you need to worry about, you can move all the complex logic to initialization (which does not matter if it takes 1 ms more). In this case, all the logic in findMethodToInvoke() will be moved to the constructor, where you will findMethodToInvoke() over all the interfaces and superclasses of each method you find and add them to your TypeMap parameter. If you perform this optimization, then findMethodToInvoke() will become one line:
return parameterTypeMap.get(test.getClass());
but without this optimization and with complete generality, here is my example of how to do this:
import java.lang.reflect.*; import java.util.*; public class Test { private final Map<Object, Method> parameterTypeMap = new HashMap<Object, Method>(); private final Object[] tests = {Double.valueOf(3.1415), Boolean.TRUE, new Date(), new GregorianCalendar(), new HashMap<Object, Object>()}; public Test() { Method[] methods = Setters.class.getMethods(); for (Method method : methods) { if (method.getName().equals("setCellValue")) { Class<?>[] clazzes = method.getParameterTypes(); if (clazzes.length != 1) { continue; } if (clazzes[0].isPrimitive()) { handlePrimitive(method, clazzes[0]); } parameterTypeMap.put(clazzes[0], method); } } }