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

痴心易碎 提交于 2020-03-18 12:55:24

问题


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
    }

 }

回答1:


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");
  }
}  



回答2:


You can consider using spring AOP with an around advice.



来源:https://stackoverflow.com/questions/60387104/is-there-a-way-to-always-execute-a-function-before-and-after-all-methods-of-a-cl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!