coder
coder

Reputation: 231

Is there a way to always execute a function before and after all methods of a class in Java?

HI I have a class below which has functions to pull data from DataServices. I want to always call a method which prints a time at which the method was called and a method which prints time after the method was executed . Basically after every method is executed i want to know how much time it took to execute each method. Is there a generic way to do it instead of adding time at start and end of every function?

class ABC {


    void getAllProducts(){
        // some logic
    }

    void getAllClients(){
        // some logic
    }

    void getAllSymbols(){
        // some logic
    }

 }

Upvotes: 8

Views: 1554

Answers (1)

Scratte
Scratte

Reputation: 3166

You can use an “Execute Around” idiom similar to this by Jon Skeet, with the timing surrounding your method call:

public class StackOverflowTest {
  public static void main(String[] args){
    StackOverflowTest test = new StackOverflowTest(); 
    test.timeMethod(test::getAllProducts);
    test.timeMethod(test::getAllClients);
    test.timeMethod(test::getAllSymbols);
  }

  void getAllProducts(){
    System.out.println("getting all Products");
  }

  void getAllClients(){
    System.out.println("getting all Clients");
  }

  void getAllSymbols(){
    System.out.println("getting all Symbols");
  }

  // The "Execute Around" method
  void timeMethod(JustDoIt justDoIt){
    long start = System.nanoTime();
    try {
      justDoIt.doIt();
    } finally {
      long end = System.nanoTime();
      System.out.println("  Time: " + (end - start) / 1000 + " microseconds"");
    }
  }  
}

@FunctionalInterface
interface JustDoIt {
  void doIt();
}

Prints:

getting all Products
  Time: 1817 microseconds
getting all Clients
  Time: 421 microseconds
getting all Symbols
  Time: 418 microseconds

If you don't want your own Interface, you can replace it with a Runnable. This example also uses System.currentTimeMillis() instead of System.nanoTime():

void timeMethod(Runnable toRun){
  long start = System.currentTimeMillis();
  try{
    toRun.run();
  } finally {
    long end = System.currentTimeMillis();
    System.out.println("  Time: " + (end - start) + " miliseconds");
  }
}  

Upvotes: 16

Related Questions