user5278445
user5278445

Reputation:

Call a method when another method is called?

Now I am very aware that you can simply do the following:

public static void methodA() {
   doSomeOtherStuffHere();
   methodB(); 
}

public static void methodB() {
    doStuffHere();
}

But in my scenario, I cannot change the code of method A ( I cannot add the methodB(); ). So is there any way I can detect when method A is called (and then execute method B when it is)?

Upvotes: 2

Views: 1489

Answers (3)

Simeon Ikudabo
Simeon Ikudabo

Reputation: 2190

in you code you have "doSomeOtherStuff()" method. You could place methodB within it. Here is an example:

public class App{

      public static boolean isCalled = true;

       public static void main( String[] args ){

              starterMethod();

       }

       public static void methodB() {
             System.out.println("Method B started");
       }

       public static void starterMethod() {
             methodB();
         }

      }

In you example you can call "doOtherStuffHere". You could call methodB within doOtherStuffHere and that method could contain a call to methodB.

Upvotes: 0

PrabaharanKathiresan
PrabaharanKathiresan

Reputation: 1129

In plain Java, you can do this by creating a subclass of the Class (Which owns methodA) and override the method methodA. Write your own Implementation and use the subclass method where ever you need.

Upvotes: 1

Ivan
Ivan

Reputation: 8758

You can use Aspect Oriented Programming (https://www.baeldung.com/aspectj) to create aspect which will be executed before YourClass.methodB()

Upvotes: 3

Related Questions