简体   繁体   中英

Java - insert println() in each method of given class

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM