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 {
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 300, 250);
        primaryStage.setTitle("Hello World!");

    public static void main(String[] args) {
    private void method_01(){
    private void method_02(){
        StackTraceElement[] stackTraceElementArray = 
        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: