Java getMethod with superclass parameters in method

后端 未结 4 518
旧时难觅i
旧时难觅i 2020-12-05 03:33

Given:

class A
{
    public void m(List l) { ... }
}

Let\'s say I want to invoke method m with reflection, passing an ArrayLis

相关标签:
4条回答
  • 2020-12-05 03:38

    See java.beans.Expression and java.beans.Statement.

    0 讨论(0)
  • 2020-12-05 03:38

    I'm guessing you want getDeclaredMethods(). Here is an example. You can dig through the list of methods and pick the one you want by name. Whether or not this is robust or a good idea is another question.

    0 讨论(0)
  • 2020-12-05 03:52

    If you know the type is List, then use List.class as argument.

    If you don't know the type in advance, imagine you have:

    public void m(List l) {
     // all lists
    }
    
    public void m(ArrayList l) {
      // only array lists
    }
    

    Which method should the reflection invoke, if there is any automatic way?

    If you want, you can use Class.getInterfaces() or Class.getSuperclass() but this is case-specific.

    What you can do here is:

    public void invoke(Object targetObject, Object[] parameters,
            String methodName) {
        for (Method method : targetObject.getClass().getMethods()) {
            if (!method.getName().equals(methodName)) {
                continue;
            }
            Class<?>[] parameterTypes = method.getParameterTypes();
            boolean matches = true;
            for (int i = 0; i < parameterTypes.length; i++) {
                if (!parameterTypes[i].isAssignableFrom(parameters[i]
                        .getClass())) {
                    matches = false;
                    break;
                }
            }
            if (matches) {
                // obtain a Class[] based on the passed arguments as Object[]
                method.invoke(targetObject, parametersClasses);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 04:03

    Instead of myList.getClass(), why not just pass in List.class? That is what your method is expecting.

    0 讨论(0)
提交回复
热议问题