繁体   English   中英

调用在其超级类中实现的类的方法

[英]Invoke a method of a class which is implemented in her supperclass

我有一个java ProductManager类,该类扩展了具有相同名称的另一个类,该类位于另一个具有另一个package(“ 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)

产品未被删除:(

如果必须使用反射,则不要使用getDeclaredMethod()因为(顾名思义)它只能返回在当前类中声明的方法,而您声称要调用在其他类中声明的方法(确切地说是在super中声明)类)。

要获取公共方法(包括继承的方法),请使用getMethod()

各种getDeclaredMethod()getDeclaredMethods()仅返回在当前类实例上声明的方法。 从javadoc:

这包括公共,受保护,默认(程序包)访问和私有方法,但不包括继承的方法。

这里的重要部分是“ 但不包括继承的方法 ”。 这就是为什么您的代码目前处于异常状态,而不是从父类返回deleteProduct()方法的原因。

相反,如果您想继续使用反射,则需要使用getMethod方法,因为它会返回所有公共方法,“ 包括那些由类或接口声明的方法以及从超类和超接口继承的方法”。

如果您要覆盖该方法,则只需使用保留字super (来自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(...) 继承的所有方法都是直接可用的。

免责声明:我不确定我是否完全理解您的问题。 我仍然会尽力回答我认为的理解。

com.franceFactory.services包中的Product (称为A )扩展了com.services包中的Product类(称为B )。

因此,A扩展了B。

B具有方法deleteProduct(java.lang.Long)

一个重写方法deleteProduct(java.lang.Long)

您具有类A的实例。因此,通过OOPS概念方法,将调用对象A的deleteProduct

除非您具有类B的实例,否则无法从外部调用super方法。

编辑

OP澄清yes, it's public, but it isn't overridden in my class

super中的方法在这里被调用。 由于该方法上写的内容,产品不会被删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM