Using reflection to obtain a method; interface type method parameters not found

Maybe I'm missing something simple here, but how do I get a method whose parameter is an interface that uses reflection.

The following case newValuewill be List<String>called foo. Therefore, I would call addModelProperty("Bar", foo);But this only works for me, if I do not use the interface and use only LinkedList<String> foo. How to use an interface for newValueand get a method from modelthat has an interface as a parameter addBar(List<String> a0)?

Here is a more detailed example. (based on: This example )

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);
}
+3
source share
2 answers

, , . , , , .

, 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 exactly one, use it. */
+11

Source: https://habr.com/ru/post/1762314/


All Articles