-5

I have created a java class which delegates all calls to another class. I want that on each method call program will output some info - method name and arguments. There are very many methods in that class, so I don't want to insert System.out.println() in each method manually. Is there any way to do it with regex?

here is a sample method with required println() line:

private final PreparedStatement statement;

@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
    System.out.println("setNull: parameterIndex=" + ", sqlType" + sqlType);
    statement.setNull(parameterIndex, sqlType);
}
eLRuLL
  • 18,488
  • 9
  • 73
  • 99
andronix
  • 124
  • 9
  • 3
    Regex? Do you know how to use regex? This sounds to me more like [loggin with AOP](http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html). – Juan Carlos Mendoza Dec 28 '17 at 13:04
  • @JuanCarlosMendoza I fell on the floor laughing when he said regex xD – Cardinal System Dec 28 '17 at 13:05
  • what in the world has regex to do with this? but yes, you should look into AOP. voting to close as a duplicate, as there are plenty already. – eis Dec 28 '17 at 13:24
  • Possible duplicate of [Logging a methods's name and parameters](https://stackoverflow.com/questions/13136790/logging-a-methodss-name-and-parameters) – eis Dec 28 '17 at 13:25
  • Well, my idea was to copy paste whole java class to some text editor which supports regular expressions like TextPad and using search/replace dialog insert in each method line of code which would print method name and arguments.. – andronix Dec 28 '17 at 19:59
  • 1
    @CardinalSystem nice to make you so happy. – andronix Dec 28 '17 at 20:02
  • Sorry, that wasn't nice. – Cardinal System Dec 28 '17 at 20:04

1 Answers1

3

For this cases and similar we do not updated every function to add println, we usually use something that called AOP (Aspect Oriented Programming).

AOP is a useful technique that enables adding executable blocks to the source code without explicitly changing it. In our example, we don't want to log method execution inside the class. Instead, we want some other class to intercept every call to method power(), measure its execution time and send this information to slf4j.

please read this for more details aop-aspectj-java-method-logging and logging-with-aop-in-spring

AOP give you ability to intercept method execution and add your logic before,after or around the execution, so in your case you can add before execution interceptor and print the msg that you want.

AOP example :

@Aspect
public class MyLogger {

    private Logger log = Logger.getLogger(getClass());

    @before("execution(* *(..))") // after execution of any function 
    public void log(JoinPoint point) {
      System.out.println(point.getSignature().getName() + " called...");
    }
} 

You can also use point.getArgs() to get all method arags

Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39