是否可以调用参数对象或参数类是子类并且方法本身将父类(super class)作为参数的方法?
我试图通过抽象类 Problem 的具体实现来调用此方法 public void setNewProblem(Problem problem);
。不幸的是,我遇到了一个 NoSuchMethodException
异常。
我这样调用调用:
Method method = model.getClass().getMethod("set" + propertyName, new Class[] { newValue.getClass() });
method.invoke(model, newValue);
如果我将 newValue.getClass()
更改为 Problem.class
一切正常。知道如何将子类传递给 public void setNewProblem(Problem problem);
吗?
最佳答案
您必须询问它的确切类型。这是因为您可以有多个可能的重载方法,并且它需要确切地知道您想要什么。
所以你可以调用一个子类,但你不能在不在场的情况下请求一个子类。
您可以做的是查看所有方法并找到匹配项。
如果您只需要属性的 setter 或 getter,我建议您查看 BeanIntrospector这将为您找到该属性的所有属性和 getter/setter 方法。
关于java - 使用子类作为方法参数调用 getMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20029005/