Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add similar functionality to a number of methods in java?

I have a lot of methods for logging, like logSomeAction, logAnotherAction etc.

Now I want all these methods make a small pause after printing messages (Thread.sleep).

If I do it manually, I would do something like this:

//before:
public static void logSomeAction () {
   System.out.println (msg(SOME_ACTION));
}

//after:
public static void logSomeAction () {
   System.out.println (msg(SOME_ACTION));
   try {
      Thread.sleep (2000);
   } catch (InterruptedException ignored) { }
}

I remember that Java has proxy classes and some other magic-making tools. Is there any way avoid copy-n-pasting N sleep-blocks to N logging methods?

like image 884
Roman Avatar asked Jan 02 '26 09:01

Roman


1 Answers

You could use Aspects to add extra "orthogonal" functionality to your methods.

If that sounds too esoteric, a simpler, down-to-earth solution would be to add the sleep in a separate method, then call that method in each of your logging methods. The first time you do this, you need to touch each method, but the next time if you want to modify the extra behaviour or add something else, you can do it in one single place.

like image 180
Péter Török Avatar answered Jan 03 '26 23:01

Péter Török



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!