Using reflection to get a method; method parameters of interface types aren't found

前端 未结 3 1592
隐瞒了意图╮
隐瞒了意图╮ 2020-12-20 23:25

How do I get a method using reflection based on a parameter value when the parameter type is an interface?

In the following case (based on this example), newVal

相关标签:
3条回答
  • 2020-12-21 00:02

    Another answer suggested using Apache Commons to get the Method object using MethodUtils.getMatchingAccessibleMethod.

    However, it looks like you're not using the Method object for anything other than immediately invoking it on an instance. This being the case, you can instead use Apache Commons Lang's MethodUtils.invokeMethod(Object object, String methodName, Object... args). Rather than just returning the Method object, this instead invokes the method on the given object.

    protected void addModelProperty(String propertyName, Object newValue) {
      try {
        MethodUtils.invokeMethod(model, "add" + propertyName, newValue);
      } catch (ReflectiveOperationException e) {
      }
    }
    
    0 讨论(0)
  • 2020-12-21 00:17

    You'll actually have to search through all the methods in your model and find those that are compatible with the arguments you have. It is a bit messy, because, in general, there might be more that one.

    If you are interested in just public methods, the getMethods() method is the easiest to use, because it gives you all accessible methods without walking the class hierarchy.

    Collection<Method> candidates = new ArrayList<Method>();
    String target = "add" + propertyName;
    for (Method m : model.getClass().getMethods()) {
      if (target.equals(m.getName())) {
        Class<?>[] params = m.getParameterTypes();
        if (params.length == 1) {
          if (params[0].isInstance(newValue))
            candidates.add(m);
        }
      }
    }
    /* Now see how many matches you have... if there's exactly one, use it. */
    
    0 讨论(0)
  • 2020-12-21 00:22

    If you don't mind adding a dependency to Apache Commons, you may use MethodUtils.getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes).

    If you mind adding this dependency, you may at least find it useful to take a look at how this method is implemented.

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