Tuesday, April 30, 2013

Get current method name using Thread.currentThread().getStackTrace()

To get the stack trace elements in StackTraceElement[] form, call Thread.currentThread().getStackTrace(). The second element, [1], is the your method call getStackTrace(); [0] is getStackTrace(). Then call its getMethodName() method to get the name of your method.

Example to print the stack trace elements, and the name of the current method.

Get current method name
Get current method name


package javafxapplication1;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXApplication1 extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                method_01();
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    private void method_01(){
        method_02();
    }
    
    private void method_02(){
        
        StackTraceElement[] stackTraceElementArray = 
                Thread.currentThread().getStackTrace();
        
        for(int i = stackTraceElementArray.length-1; i >= 0; i--){
            System.out.println(i + ":" + stackTraceElementArray[i].getMethodName());
        }
        
        String me = Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("It's: " + me);
    }
}


1 comment: