Running a method after the constructor of any derived class

前端 未结 6 963
时光说笑
时光说笑 2020-12-31 00:07

Let\'s say I have a Java class

abstract class Base {
    abstract void init();
    ...
}

and I know every derived class will have to call <

相关标签:
6条回答
  • 2020-12-31 00:10

    What happens in init()? It's likely that a better design could eliminate the method altogether, or at least relax the requirement that it execute after the sub-class' constructor. Be certain that init() does not make the object under construction visible to any other threads before the constructor completes, because that creates concurrency bugs.

    As an (ugly) alternative, an abstract method could be implemented by sub-classes as a pseudo-constructor:

    abstract class Base {
      Base() {
        ctor();
        init();
      }
      abstract void ctor();
      abstract void init();
    }
    
    0 讨论(0)
  • 2020-12-31 00:17

    Or use spring... you can do <beans default-init-method="init">, see Default initialization and destroy methods.

    0 讨论(0)
  • 2020-12-31 00:21

    In addition to Bozho's recommendation, an application container is excellent for the task.

    Mark your init() method with the javax.annotation.PostConstruct annotation and a rightly configured EJB or Spring container will execute the method after the dependency injections are finished, but before the object can be used by the application.

    An example method:

    @PostConstruct
    public void init() { 
        // logic..
    }
    

    In an enterprise application you can open resources to for example the files system in the init() method. This initialization can throw exceptions and should not be called from a constructor.

    0 讨论(0)
  • 2020-12-31 00:29

    Avoid this. If you do it, any class that extends your DerivedX class may decide to also call init() thus leaving the object in inconsistent state.

    One approach is to let the init() method be invoked manually by clients of your class. Have an initialized field, and throw IllegalStateExcepion if any method that requires initialization is called without it.

    A better approach would be to use a static factory method instead of constructors:

    public Derived2 extends Base {
        public static Derived2 create() {
           Derived2 instance = new Dervied2();
           instance.init();
           return instance;
        }
    }
    

    Update: As you suggest in your update, you can pass Builder to a static factory method, which will call the init() on the instance. If your subclasses are few, I think this is an overcomplication, though.

    0 讨论(0)
  • 2020-12-31 00:29

    if Java had it, we wouldn't see all these init() method calls in the wild.

    "surround child constructor with something" - that cannot be done in pure java. Too bad, because there can be very interesting applications, especially with anonymous class + instance initialization block.

    factory and container - they can be helpful when native new doesn't do the job; but that's trivial and boring, and won't work with anonymous classes.

    0 讨论(0)
  • 2020-12-31 00:32

    If you are adverse to using factories for some reason, you could use the following trick:

    trait RunInit {
        def init():Unit
        init()
    }
    
    class Derived1 extends Base with RunInit {
        def init() = println("INIT'ing!")
    }
    

    This will run init() before the Derived1 constructor/body.

    0 讨论(0)
提交回复
热议问题