简体   繁体   English

Java如何编写通用实用程序以打印所有功能的当前执行功能名称?

[英]Java How to Write a Common Util to Print the Currently Executed Function Name For All Functions?

I'm new to Java. 我是Java新手。 I want to print the function names for quite a few functions that I run. 我想为我运行的许多功能打印功能名称。 Here is my current code which I found very repetitive in every single function. 这是我当前的代码,我发现每个函数中都非常重复。 Is there a way (such as annotations) to make the code more concise and reusable? 有没有办法(例如注释)使代码更简洁和可重用?

I want to create such a common utility for all classes, instead of a single class. 我想为所有类而不是单个类创建一个通用的实用程序。

class SomeClass {
    void func1() {
        String methodName = new Exception().getStackTrace()[0].getMethodName();
        System.out.println(methodName);
        // execute func1
    }
    void func2() {
        String methodName = new Exception().getStackTrace()[0].getMethodName();
        System.out.println(methodName);
        // execute func2
    }
    void func3() {
        String methodName = new Exception().getStackTrace()[0].getMethodName();
        System.out.println(methodName);
        // execute func3
    }
}

I have tried to create another class to wrap the repetitive lines as below. 我试图创建另一个类来包装重复行,如下所示。

class FuncInfo {
    public void printFuncName() {
        String methodName = new Exception().getStackTrace()[0].getMethodName();
        System.out.println(methodName);
    }
}
class SomeClass {
    FuncInfo funcInfo = new FuncInfo();
    void func1() {
        funcInfo.printFuncName;
        // execute func1
    }
   // ...
}

However, it prints the common util class and function names ("printFuncName"), instead of the method names that I need ("func1", "func2" or "func3"). 但是,它将打印通用的util类和函数名称(“ printFuncName”),而不是我需要的方法名称(“ func1”,“ func2”或“ func3”)。

You can delegate this task to a commonly used function: 您可以将此任务委派给常用功能:

class SomeClass() {
    void fun() {
        String methodName = new Exception().getStackTrace()[1].getMethodName();
        System.out.println(methodName);
        // execute func1
    }
    void func1() {
        fun();
        // execute func1
    }
    void func2() {
        fun();
        // execute func2
    }
    void func3() {
        fun();
        // execute func3
    }
}

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

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