Getting the name of the currently executing method

前端 未结 22 2205
闹比i
闹比i 2020-11-22 03:33

Is there a way to get the name of the currently executing method in Java?

相关标签:
22条回答
  • 2020-11-22 04:27

    What's wrong with this approach:

    class Example {
        FileOutputStream fileOutputStream;
    
        public Example() {
            //System.out.println("Example.Example()");
    
            debug("Example.Example()",false); // toggle
    
            try {
                fileOutputStream = new FileOutputStream("debug.txt");
            } catch (Exception exception) {
                 debug(exception + Calendar.getInstance().getTime());
            }
        }
    
        private boolean was911AnInsideJob() {
            System.out.println("Example.was911AnInsideJob()");
            return true;
        }
    
        public boolean shouldGWBushBeImpeached(){
            System.out.println("Example.shouldGWBushBeImpeached()");
            return true;
        }
    
        public void setPunishment(int yearsInJail){
            debug("Server.setPunishment(int yearsInJail=" + yearsInJail + ")",true);
        }
    }
    

    And before people go crazy about using System.out.println(...) you could always, and should, create some method so that output can be redirected, e.g:

        private void debug (Object object) {
            debug(object,true);
        }
    
        private void dedub(Object object, boolean debug) {
            if (debug) {
                System.out.println(object);
    
                // you can also write to a file but make sure the output stream
                // ISN'T opened every time debug(Object object) is called
    
                fileOutputStream.write(object.toString().getBytes());
            }
        }
    
    0 讨论(0)
  • 2020-11-22 04:30

    I don't know what is the intention behind getting the currently executed method's name, but if that's just for debugging purpose, then logging frameworks like "logback" can help here. For example, in logback, all you need to do is to use the pattern "%M" in your logging configuration. However, this should be used with caution as this may degrade performance.

    0 讨论(0)
  • 2020-11-22 04:32
    String methodName =Thread.currentThread().getStackTrace()[1].getMethodName();
    System.out.println("methodName = " + methodName);
    
    0 讨论(0)
  • 2020-11-22 04:33
     public class SomeClass {
       public void foo(){
          class Local {};
          String name = Local.class.getEnclosingMethod().getName();
       }
     }
    

    name will have value foo.

    0 讨论(0)
  • 2020-11-22 04:33

    The fastest way I found is that:

    import java.lang.reflect.Method;
    
    public class TraceHelper {
        // save it static to have it available on every call
        private static Method m;
    
        static {
            try {
                m = Throwable.class.getDeclaredMethod("getStackTraceElement",
                        int.class);
                m.setAccessible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static String getMethodName(final int depth) {
            try {
                StackTraceElement element = (StackTraceElement) m.invoke(
                        new Throwable(), depth + 1);
                return element.getMethodName();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    

    It accesses the native method getStackTraceElement(int depth) directly. And stores the accessible Method in a static variable.

    0 讨论(0)
  • 2020-11-22 04:33

    Use the following Code :

        StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
        StackTraceElement e = stacktrace[1];//coz 0th will be getStackTrace so 1st
        String methodName = e.getMethodName();
        System.out.println(methodName);
    
    0 讨论(0)
提交回复
热议问题