在inheritance的情况下使用model.getClass()。getMethod的问题
我正在关注Oracle Network上的这篇文章 ,以便在开发桌面应用程序时实现MVC。 我有一个问题:我正在使用由SimpleDirectory
和WildcardDirectory
扩展的抽象Directory类。 其中一个模型管理器方法接受Directory作为参数:
public void addDirectoryDummy(Directory d){ System.out.println("Hello!"); }
抽象控制器使用setModelProperty来调用此方法:
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(); } } }
我从我的实际控制器中调用它,如下所示:
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
遗漏了一些东西。
编辑:我已经阅读了文档,并在getMethod
说
parameterTypes参数是一个Class对象数组,它按声明的顺序标识方法的forms参数类型。
所以我猜这就是问题所在。
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 { }
package com.test; import java.lang.reflect.Method; 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 { Method method = test.getClass().getMethod("doSomething", new Class[] { child.getClass().getSuperclass() }); method.invoke(test, child); System.out.println("This works"); } 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 { }
您需要将.getSuperclass()添加到child