我有一个java ProductManager类,它扩展了同名的另一个类,它位于另一个带有另一个包(“com.services”)的项目中。
我必须调用位于超类中的方法deleteProduct(Long productId)。
try{
Object service = CONTEXT.getBean("ProductManager");
Method method = service.getClass().getDeclaredMethod("deleteProduct", Long.class);
method.invoke(service, productId);
} catch(Exception e){
log.info(e.getMessage());
}
我无法删除该产品:我得到了以下信息:
com.franceFactory.services.ProductManager.deleteProduct(java.lang.Long)
该产品未被删除:
发布于 2014-10-13 13:42:43
各种getDeclaredMethod()
和getDeclaredMethods()
只返回在当前类实例上声明的方法。来自javadoc:
这包括公共、受保护、默认(包)访问和私有方法,但不包括继承的方法。
这里的重要部分是“但不包括继承的方法”。这就是为什么在当前的代码中出现异常的原因,它不会从父类返回deleteProduct()
方法。
相反,如果您想继续使用反射,则需要使用getMethod
方法,因为它返回所有公共方法,“包括类或接口声明的方法以及从超类和超级接口继承的方法”。
发布于 2014-10-13 13:35:57
如果必须使用反射,那么就不要使用getDeclaredMethod()
,因为(顾名思义)它只能返回在当前类中声明的方法,而您声称要调用在其他类中声明的方法(准确地说是在超类中声明的)。
要获得公共方法(包括继承的方法),请使用getMethod()
。
发布于 2014-10-13 13:30:07
如果要重写该方法,只需使用保留字超级 (来自Oracle ):
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod(); // This calls to the method defined in the superclass
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
此代码将编写:
用超阶级印刷的。 打印成子类
在其他情况下(您没有覆盖它,只是使用它),只需编写this.methodName(...)
即可。继承的所有方法都是直接可用的。
https://stackoverflow.com/questions/26341012
复制相似问题