使用反射来获得方法; 找不到接口类型的方法参数

ini*_*ero 3 java reflection

也许我在这里缺少一些简单的东西,但是如何获得一个方法,其参数是使用反射的接口.

在下面的例子newValue中将被List<String>称为foo.所以我会打电话addModelProperty("Bar", foo);但是这只适用于我,如果我不使用界面,只使用LinkedList<String> foo.如何使用接口newValue并从中获取model具有接口作为参数的方法addBar(List<String> a0)

这是一个更详细的例子.(基于:此示例)

public class AbstractController {
  public setModel(AbstractModel model) {
    this.model = model;
  }
  protected void addModelProperty(String propertyName, Object newValue) {
    try {
      Method method = getMethod(model.getClass(), "add" + propertyName, newValue);
      method.invoke(model, newValue);
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (Exception e) {}
    }
}

public class AbstractModel {
  protected PropertyChangeSupport propertyChangeSupport;
  protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
    propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
  }
}

public class Model extends AbstractModel {
  public void addList(List<String> list) {
    this.list.addAll(list);
  }
}

public class Controller extends AbstractController {
  public void addList(List<String> list) {
    addModelProperty(list);
  }
}

public void example() {
  Model model = new Model();
  Controller controller = new Controller();
  List<String> list = new LinkedList<String>();
  list.add("example");
// addList in the model is only found if LinkedList is used everywhere instead of List
  controller.addList(list);
}
Run Code Online (Sandbox Code Playgroud)

eri*_*son 11

您实际上必须搜索模型中的所有方法,并找到与您拥有的参数兼容的方法.这有点乱,因为一般来说,可能会有更多.

如果您只对公共方法感兴趣,那么该getMethods()方法最容易使用,因为它为您提供了所有可访问的方法,而无需遍历类层次结构.

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. */
Run Code Online (Sandbox Code Playgroud)


Lod*_*vik 6

如果您不介意向Apache Commons添加依赖项,您可以使用MethodUtils.getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes).

如果您介意添加此依赖项,您至少可能会发现查看此方法的实现方式很有用.