在继承的情况下使用model.getClass()。getMethod的问题 [英] Problem using model.getClass().getMethod in case of inheritance
问题描述
我正在关注Oracle网络上的文章在开发桌面应用程序时实现MVC。
我有一个问题,但是:我正在使用一个由 SimpleDirectory
扩展的抽象目录类和 WildcardDirectory
。其中一个模型管理器方法接受一个Directory作为参数:
I'm following this article on Oracle Network to implement MVC when developing desktop applications.
I have a problem, though: I'm using an abstract Directory class extended by SimpleDirectory
and WildcardDirectory
. One of the model manager method accepts a Directory as argument:
public void addDirectoryDummy(Directory d){
System.out.println("Hello!");
}
抽象控制器使用setModelProperty来调用此方法:
The abstract controller uses a setModelProperty to call this method:
protected void setModelProperty(String propertyName, Object newValue) {
for (AbstractModel model: registeredModels) {
try {
Method method = model.getClass().
getMethod(propertyName, new Class[] {
newValue.getClass()
}
);
method.invoke(model, newValue);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
我从我的实际调用它控制器是这样的:
I call it from my actual controller like this:
public void dummy( Directory d){
setModelProperty( BACKUP_DUMMY, d );
}
在我看来,我有:
this.controller.dummy( new SimpleDirectory(0,"ciao") );
我有以下错误:
java.lang.NoSuchMethodException: it.univpm.quickbackup.models.BackupManager.addDirectoryDummy(it.univpm.quickbackup.models.SimpleDirectory)
at java.lang.Class.getMethod(Class.java:1605)
如何解决这个问题?我在使用 getMethod
时遗漏了一些东西。
How do I solve this problem? I'm missing something in the usage of getMethod
.
编辑:我读过 docs 和 getMethod
它说
parameterTypes parameter是一个Class对象数组,用于标识方法的形式参数类型
,声明顺序为
。
The parameterTypes parameter is an array of Class objects that identify the method's formal parameter types, in declared order.
所以我猜这就是问题所在。
So I'm guessing that's the problem.
推荐答案
public class Test
{
public static void main(String[] args) throws Exception {
Test test = new Test();
Child child = new Child();
// Your approach, which doesn't work
try {
test.getClass().getMethod("doSomething", new Class[] { child.getClass() });
} catch (NoSuchMethodException ex) {
System.out.println("This doesn't work");
}
// A working approach
for (Method method : test.getClass().getMethods()) {
if ("doSomething".equals(method.getName())) {
if (method.getParameterTypes()[0].isAssignableFrom(child.getClass())) {
method.invoke(test, child);
}
}
}
System.out.println("This works");
}
public void doSomething(Parent parent) {
}
}
class Parent {
}
class Child extends Parent {
}
这篇关于在继承的情况下使用model.getClass()。getMethod的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!