【发布时间】:2011-04-05 20:51:54
【问题描述】:
当参数类型为接口时,如何根据参数值获取使用反射的方法?
在以下情况下(基于this example),newValue 将是称为foo 的List<String>。所以我会打电话给addModelProperty("Bar", foo); 但这仅适用于我不使用界面且仅使用LinkedList<String> foo 的情况。如何使用newValue 的接口并从model 获取具有接口作为参数addBar(List<String> a0) 的方法?
public class AbstractController {
private final AbstractModel model;
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) {}
}
private Method getMethod(Class clazz, String name, Object parameter) {
return clazz.getMethod(name, parameter.getClass());
}
}
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);
}
【问题讨论】:
-
为什么不发布您尝试过但不起作用的代码,以便我们了解您希望它如何工作?
标签: java methods reflection interface subclass