Call a method after the constructor has ended

spring call method after bean initialization
java constructor
spring framework call method after initialization
postconstruct annotation
alternate constructor java
spring call method before bean initialization
can a class have 2 constructors
how to call a constructor in java

I need to call a method after the constructor has ended and I have no idea how to do. I have this class:

Class A {
    public A() {
        //...
    }

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

Always execute method after constructor in Java, Golang has something like defer that lets you run a piece of code after the function/method/constructor is done. share. Share a link to this question. Copy link When for example a string has to be returned from a class that needs to be called then a method could be created, i.e. a constructor will not be sufficient as this will not return anything. Ugg. Look, there are constructors that "return" strings just fine.

You will need a static factory method to construct the object, call the init method, and finally return the object:

class A {
    private A() {
        //...
    }

    private void init() {
        //Call after the constructor
    }

    public static A create() {
        A a = new A();
        a.init();
        return a;
    }
}

Notice I have made the constructor and the init() method private, so that they can only be accessed by the factory method. Client code would make objects by calling A.create() instead of calling the constructor.

Force other developers to call method after completing their work , The pragmatic solution is to make the class AutoCloseable , and provide a finalize() method as a backstop (if appropriate see below!) And you can't "call" a constructor anyway, other than implicitly thru creating a new object via the "new" keyword. If you want to "re-initialize" the state, then create a (non-overrideable) method called initialize () and call that from both your constructor and from this multiplyByZero method.

What did you so far? Are you looking something like this?

  Class A {
        public A() {
            //...
        }

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

     public static void main(String[] args)
    {
    A a = new A();

    a.init();
}

Non-final method invocation in constructor - Java queries, If a constructor calls a method that is overridden in a subclass, it can cause the overriding method in the subclass to be called before the subclass has been� The subclass constructor must specify these arguments in the call to the superclass constructor and must use the constructor output argument to form the call. Here is the syntax: classdef MyClass < SuperClass methods function obj = MyClass(a,b,c,d) obj@SuperClass(a,b); end end end

I pick up some ideas and provide an abstractable solution:

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

Can we call a constructor directly from a method in java?, No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line� A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object. Learn about Java Constructor, Constructor Overloading and Chaining with examples in this tutorial.

If you want to call method BEFORE constructor you can use initializer block. https://www.geeksforgeeks.org/g-fact-26-the-initializer-block-in-java/

class A {
    { 
        init() 
    }

    public A() {
        //todo
    }

    private final void init() {
       //todo
    }
}

Constructors in Java - A complete study!!, In short constructor and method are different(More on this at the end of this guide) . your class Demo it cannot be called default constructor since you have written obj2 I have passed two arguments so that this constructor gets invoked after� A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation.

Initialization and Cleanup — Python 3 Patterns, Recipes and Idioms, Calling the base-class constructor first, how to do it using super(), why you should always call it An excellent example of the subtleties of initialization is static fields in classes. Without the explicit call to del , __del__ is only called at the end of the program, Use an explicit finalizer method, such as close() for file objects. Static .NET method call. To invoke a static .NET method from JavaScript, use the DotNet.invokeMethod or DotNet.invokeMethodAsync functions. Pass in the identifier of the static method you wish to call, the name of the assembly containing the function, and any arguments. The asynchronous version is preferred to support Blazor Server scenarios.

2.3. Calling Methods Without Parameters — AP CS Awesome, An object method must be called on an object of the class that the method is end class. 4. yertle.forward();. 5. World world = new World(300,300);. 6. yertle. Methods are defined after the instance variables (attributes) and constructors in a � Overloads Shared Sub New() End Sub Overloads Shared Sub New(ByVal ID As Integer) End Sub. After dealing with the shared constructor, the runtime executes any virtual constructor (a constructor that is not shared), passing in the optional arguments, for the specific instance of the class. After that is completed, the instance is ready for use.

Call Superclass Methods on Subclass Objects, If you want the superclass constructor called with specific arguments, In the following class, the MySub object is initialized by the MySuperClass constructor. end end end. B) It will call the constructor of ClassA that receives an integer as an argument. C) It will call the method named super and pass the value 10 to it as an argument. D) The method super will have to be defined before we can say what will happen.

Comments
  • Some answers seem to be assuming that the init can simply be moved inside the constructor, but I assume that whatever it is doing is not appropriate to be done in the constructor (such as registering listeners, which would then have a chance to see a partially constructed object), otherwise there would be no need for the question.
  • If init() starts a new thread or shares its this reference with another class that may access the reference from another thread, you should not call it in the constructor. If you do, you'll have a data race.
  • The same problem applies if you do it directly in the constructor. There's no difference if you delegate part of the construction to the init method. What is a problem is when the init method may be overridden by subclasses.
  • You probably want to make the init method private as well if you go the static factory method route. It does make a difference if the issue is sharing the this reference with other threads, since once the constructor completes the class's invariants are presumably ensured and particularly any final fields will be guaranteed to be visible from other threads.
  • @aioobe The fact that inlining it also has that bug doesn't detract from my comment, imho. init() methods often publish this or spin off threads -- that's commonly why they're separate methods as opposed to just being in the constructor. Given that the construct-than-init pattern has a relatively high correlation with init-does-thread-stuff, I thought it'd be helpful to point that danger out explicitly.
  • Well, I guess we just won't see eye to eye on the relevance of my comment, then. So I'll just leave it as a note to the OP: if your init() method exposes this to anyone (another thread, another class, etc) you're exposing yourself to subtle data race bugs. Do so at your own peril.
  • Good idea, but you don't need a factory, if the stuff is private. You could simply call it at the end of the constructor. But you can use a factory as a good solution, if the method and constructor are protected, to ensure, that overriding the constructor does not result in a missing init() call. EDIT of course, if the constructor is protected and the class is abstractable, you need a more generic factory method - forgot to mention that.
  • @UniversE No, you can't simply call it at the end of the constructor. Java makes special guarantees about the visibility of final fields after the constructor has completed. If you pass a reference to the object to another thread, it could see default values for those fields, which cannot happen after the constructor has finished.
  • But if you call it at the end of the constructor, the method would execute on the same thread, and there would be no visibility issues.
  • @aioobe if you call it at the end of the constructor, and init() lets a reference to this escape, another thread could examine the object before the constructor finishes. See yshavit's comments on another answer to this question.
  • Letting this escape before the object has been fully initialized is a terrible idea, regardless if it's done from the constructor or from an init method, and regardless if there are multiple threads or not.
  • As far as I can tell, this is the only answer working with inheritance. Or am I wrong?
  • @GeorgeXavier you are right, thanks for pointing that out. Edited the answer so this is obvious now.
  • The constructor is not complete in this case. The constructor completes AFTER this.init() is run. In general, it is not good practice to run methods using this inside its own constructor because the constructor is not fully created. Usually this messes things up when you have multiple threads.