调用在她的超类中实现的类的方法

时间:2014-10-13 13:21:34

标签: java reflection

我有一个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)

产品未被删除:(

4 个答案:

答案 0 :(得分:1)

如果你必须使用反射,那么不要使用getDeclaredMethod(),因为(顾名思义)它只返回当前类中声明的方法,而你声称你想要调用在其他类中声明的方法(在超类中精确声明)。

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

答案 1 :(得分:1)

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

  

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

这里的重要部分是“但不包括继承的方法”。这就是为什么你的代码目前正在获得异常,它没有从父类返回deleteProduct()方法。

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

免责声明:我不确定我完全理解你的问题。我仍然会尝试回答我认为我理解的内容。

Product中的com.franceFactory.services(让我们称之为A) 扩展包Product中的com.services类(让我们称之为B

所以A扩展B。

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

A覆盖方法deleteProduct(java.lang.Long)

你有A类的实例。因此,对象A的OOPS概念方法deleteProduct将被调用。

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

修改

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

super中的方法在这里被调用。该产品不会因为该方法上的内容而被删除。