构造函数结束后调用方法

我需要在构造函数结束后调用一个方法,我不知道该怎么做。 我有这堂课:

Class A { public A() { //... } public void init() { //Call after the constructor } } 

您必须在客户端执行此操作,如下所示:

 A a = new A(); a.init(); 

或者您必须在构造函数的末尾执行此操作:

 class A { public A() { // ... init(); } public final void init() { // ... } } 

但是,不推荐使用第二种方法,除非您将方法设为私有或最终方法。


另一种选择可能是使用工厂方法:

 class A { private A() { // private to make sure one has to go through factory method // ... } public final void init() { // ... } public static A create() { A a = new A(); a.init(); return a; } } 

相关问题:

  • 构造函数中的可覆盖方法调用有什么问题?
  • 基础构造函数的Java调用基方法

您将需要一个静态工厂方法来构造对象,调用init方法,最后返回对象:

 class A { private A() { //... } private void init() { //Call after the constructor } public static A create() { A a = new A(); a.init(); return a; } } 

注意我已将构造函数和init()方法设为私有,因此只能通过工厂方法访问它们。 客户端代码通过调用A.create()而不是调用构造函数来创建对象。

你到目前为止做了什么? 你看起来像这样吗?

  Class A { public A() { //... } public void init() { //Call after the constructor } } public static void main(String[] args) { A a = new A(); a.init(); } 

我提出了一些想法并提供了一个可抽象的解决方案:

 class A { protected A() { // ... } protected void init() { // ... } public static  T create(Class type) { try { T obj = type.newInstance(); obj.init(); return obj; } catch (ReflectiveOperationException ex) { System.err.println("No default constructor available."); assert false; return null; } } } 

为什么不这样:

 Class A { public A() { //... Do you thing this.init(); } public void init() { //Call after the constructor } } 

怎么回事:

 Class A { public A() { // to do init(); } public void init() { //Call after the constructor } }