简体   繁体   English

自动调用超类方法

[英]Call super class method automatically

Consider the following class 考虑以下课程

class A{
    public void init(){
        //do this first;
    }
    public void atEnd(){
        //do this after init of base class ends
    }
}

class B1 extends A{

    @Override
    public void init()
    {
        super.init();
        //do new stuff.
        //I do not want to call atEnd() method here...
    }
}

I have several B1, B2,... Bn child classes which are already developed. 我有几个B1,B2,... Bn子类已经开发。 All of them extend class A. If I want to add a new functionality in all of them, the best place to do so is define that in a method within class A. But the condition is that the method should always get called automatically just before the init() method of child class ends. 它们全部都扩展了类A。如果我想在所有类中添加新功能,最好的方法是在类A中的方法中进行定义。但是条件是该方法应始终在该方法被自动调用之前子类的init()方法结束。 One basic way to do so is to again add atEnd() method call at end of init() method of child classes. 一种基本方法是在子类的init()方法末尾再次添加atEnd()方法调用。 But is there any other way to do this smartly ?? 但是还有其他方法可以巧妙地做到这一点吗?

One way to do this is by making init() final and delegating its operation to a second, overridable, method: 一种方法是使init() final,然后将其操作委托给第二个可重写的方法:

abstract class A {
  public final void init() {
    // insert prologue here
    initImpl();
    // insert epilogue here
  }
  protected abstract void initImpl();
}

class B extends A {
  protected void initImpl() {
    // ...
  }
}

Whenever anyone calls init() , the prologue and epilogue are executed automatically, and the derived classes don't have to do a thing. 每当有人调用init() ,都会自动执行序言和结语,并且派生类不必执行任何操作。

Another thought would be to weave in an aspect. 另一个想法是编织一个方面。 Add before and after advice to a pointcut. 在建议之前和之后添加切入点。

Make init() final , and provide a separate method for people to override that init() calls in the middle: 使init() final ,并为人们提供一个单独的方法来覆盖中间的init()调用:

class A{
    public final void init(){
        //do this first;
    }

    protected void initCore() { }

    public void atEnd(){
        //do this after init of base class ends
    }
}

class B1 extends A{

    @Override
    protected void initCore()
    {
        //do new stuff.
    }
}

The other answers are reasonable workarounds but to address the exact question: no, there is no way to do this automatically. 其他答案是合理的解决方法,但可以解决一个确切的问题:不,没有办法自动执行此操作。 You must explicitly call super.method() . 您必须显式调用super.method()

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

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