load 方法在 Java 最后调用另一个方法

load method calls another method at the end in Java

我有一个抽象 class Task 有两个方法 execute()finish() 如下:

abstract class Task {
  abstract void execute();

  private void finish() {
    // Do something...
  }
}

如何确保 Task 的子 class 中的重载方法 execute() 隐式 调用 finish() 作为最后声明?

我认为 'forcing' sub-classes 没有任何方法可以调用方法,但您可以尝试某种 模板方法 方法:

abstract class Foo {
  protected abstract void bar();     // <--- Note protected so only visible to this and sub-classes

  private void qux() {
    // Do something...
  }

  // This is the `public` template API, you might want this to be final
  public final void method() {
    bar();
    qux();
  }
}

public method 是 entry-point 并调用抽象 bar 然后是私有 qux 方法,这意味着任何 sub-classes 遵循模板模式。然而,这当然不是万灵药 - sub-class 可以简单地忽略 public method.

你可以创建一个实现[AutoCloseable]接口的ExecutorCloseableclass,例如:

public class ExecutorCloseable extends Foo implements AutoCloseable 
{
  @Override
  public void execute() 
  {
    // ...
  }

  @Override           //this one comes from AutoCloseable
  public void close() //<--will be called after execute is finished
  {
     super.finish();
  }
 }

你可以这样称呼它(愚蠢的 main() 例子):

 public static void main(String[] args) 
 {
     try (ExecutorCloseable ec = new ExecutorCloseable ()) 
     {

        ec.execute();

     } catch(Exception e){
        //...
     } finally {
       //...
    }
 }

希望它有意义,我真的不知道你如何调用这些方法,也不知道你如何创建 classes。但是,嘿,这是一个尝试:)

要实现这一点,Foo 上的 finish() 方法应该是 protectedpublic(推荐第一个)。