0

is there a good way to create a utils that we will call the name of the method in which it was used?

    @NoArgsConstructor(access = PRIVATE)
    public class NameUtils {
    
    public static String getMethodName(){
    ...
    }
    }
    
    public class MyClass {
    
    public void methodName(){
    
    String name = NameUtils.getMethodName()   //should return 'methodName'
    }
    }
pawello12
  • 17
  • 5
  • You should be able to get it from the stack trace which you can get via `Thread.currentThread().getStackTrace()`. – Thomas May 17 '23 at 06:55

1 Answers1

0

You can get the current stack trace from Thread.currentThread().getStackTrace() and analyse it to get the information you need.

Thanks to user16320675 and Holger who pointed out that my initial solution was uneccessary complex.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • 1
    really *schauderhaft* ;-) better use [`Thread#getStackTrace`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Thread.html#getStackTrace()) instead of throwing and catching an Exception – user16320675 May 17 '23 at 07:48
  • 2
    Why not analyze the stack trace right after you created the exception? Throwing and catching the exception does not add anything useful to the process. Of course, it’s even clearer when you call [`Thread.getStackTrace()`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Thread.html#getStackTrace()). That method also does just `new Exception().getStackTrace()` under the hood, but using the method better documents the intention. Or use [`StackWalker`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/StackWalker.html) to only process *one* stack frame. – Holger May 17 '23 at 08:57