Here's how to get the name of the Class.method()
that invoked a MyClass()
constructor.
public static void main(String[] args) {
new MyClass();
}
public MyClass() {
StackTraceElement[] stackTrace = new Exception().getStackTrace();
System.out.println(stackTrace[1]); // prints MyClass.main(MyClass.java:7)
}
We throw an exception but catch it in time As pointed by @Henrik below, we don't need to throw exceptions to inspect the stacktrace. But, if required we can further parse the captured invoker method text to remove the name of the Java file as follows.
System.out.println(
stackTrace[1].toString().split("\\(")[0]+"()"); // prints MyClass.main()