Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like @PostConstruct in plain java?

Tags:

java

I have an class A and B like this:

public static class A {
    public A() {
        System.out.println("A");
    }

    public void init() {
        System.out.println("RUN AFTER CONSTRUCTOR");
    }
}

public static class B extends A {
    public B() {
        System.out.println("B");
    }
}

public static void main(String[] args) {
    new B();
}

I want that A and all subclasses of A run a piece of code AFTER the constructor has finished.

Is it possible without adding Spring/AspectJ or something like that?

like image 991
wutzebaer Avatar asked May 11 '26 17:05

wutzebaer


1 Answers

No. Plain Java doesn't provide similarly hook methods.
@PostConstruct available in bean containers was initially designed to perform an init processing after dependency injection is done.
As the container performs for you the instantiation (and the destruction) of the beans, it has so a way to execute code after their instantiation (or before their destruction : @PreDestroy).

But i don't want to repeat it in every subclass, and it should be called after even the subclass constructor has finished

If each constructor invocation of the hierarchy has to perform a specific processing, you have to specify that in each class or base class.

like image 92
davidxxx Avatar answered May 13 '26 08:05

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!