简体   繁体   English

Java - 在给定类的每个方法中插入 println()

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

I have created a java class which delegates all calls to another class.我创建了一个 java 类,它将所有调用委托给另一个类。 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.该类中有很多方法,所以我不想在每个方法中手动插入System.out.println() Is there any way to do it with regex?有没有办法用正则表达式做到这一点?

here is a sample method with required println() line:这里是一个示例方法所需的println()行:

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) .对于这种情况和类似情况,我们不会更新每个函数以添加 println,我们通常使用称为AOP(面向方面​​编程)的东西

AOP is a useful technique that enables adding executable blocks to the source code without explicitly changing it. AOP是一种有用的技术,它可以在不显式更改源代码的情况下将可执行块添加到源代码中。 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.相反,我们希望某个其他类拦截对方法 power() 的每次调用,测量其执行时间并将此信息发送到 slf4j。

please read this for more details aop-aspectj-java-method-logging and logging-with-aop-in-spring请阅读本文以获取更多详细信息aop-aspectj-java-method-logginglogging-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使您能够拦截方法执行并在执行之前、之后或周围添加逻辑,因此在您的情况下,您可以在执行之前添加拦截器并打印所需的 msg。

AOP example : AOP示例:

@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您还可以使用point.getArgs()获取所有方法参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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