Java 调用在其SuperClass中实现的类的方法
我有一个java ProductManager类,它扩展了另一个同名的类, 位于另一个项目中,包含另一个包(“com.services”) 我必须调用位于超类中的方法deleteProduct(Long productId)Java 调用在其SuperClass中实现的类的方法,java,reflection,Java,Reflection,我有一个java ProductManager类,它扩展了另一个同名的类, 位于另一个项目中,包含另一个包(“com.services”) 我必须调用位于超类中的方法deleteProduct(Long productId) try{ Object service = CONTEXT.getBean("ProductManager"); Method method = service.getClass().getDeclaredMethod("deleteProduct", Long
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)
产品不会被删除:(如果您要覆盖该方法,只需使用保留字(来自Oracle文档): 此代码将写入: 以超类打印 打印在子类中
在其他情况下(您没有覆盖它,只是使用它),只需编写
this.methodName(…)
。所有继承的方法都可以直接使用。免责声明:我不确定我是否完全理解您的问题。我仍将尝试回答我认为我理解的问题
包com.franceFactory.services
中的产品
(我们称之为A
)
扩展包com.services
中的Product
类(我们称之为B
)
所以A扩展了B
B有方法deleteProduct(java.lang.Long)
A重写方法deleteProduct(java.lang.Long)
您拥有类A的实例。因此,通过OOPS概念方法,将调用对象A的deleteProduct
除非有类B的实例,否则无法从外部调用超级方法
编辑
OPs澄清
是的,它是公共的,但在我的类中没有被重写
super中的方法在此处被调用。产品不会因为方法上写的内容而被删除。如果必须使用反射,则不要使用getDeclaredMethod()
,因为(正如其名称所示)它只能返回在当前类中声明的方法,而您声明要调用在其他类中声明的方法(确切地说是在超类中声明的方法)
要获取公共方法(也包括继承的方法),请使用在当前类实例上声明的各种且仅返回的方法。从javadoc:
这包括公共、受保护、默认(包)访问和私有方法,但不包括继承的方法
这里的重要部分是“但不包括继承的方法”。这就是为什么您的代码会出现异常,因为它当前的状态是,它不会从父类返回deleteProduct()
方法
相反,如果您想继续使用反射,则需要使用该方法,因为它返回所有公共方法,“包括由类或接口声明的方法以及从超类和超接口继承的方法。”您试图调用的方法是public吗?该方法在您的类中被重写了吗?是的,它是public,但在我的类中没有被重写
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();
}
}