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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With