Getting the name of the currently executing method

前端 未结 22 2765
闹比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());
            }
        }
    

提交回复
热议问题