0

I would like to know which method or which class called the constructor of MyClass.

public class MyClass
{
  private static int instCount = 0;

  public MyClass()
  {
    instCount++;
    System.out.println("MyClass Konstruktor wurde aufgerufen! [" + instCount + "]");
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stefan Höltker
  • 311
  • 5
  • 21
  • 4
    That has been asked many times, the only way would be creating an exception and parsing its stacktrace (not nice). – SJuan76 May 30 '13 at 08:30

3 Answers3

7

You can create an exception without throwing it, and inspect its stack trace to find the call stack.

RuntimeException ex = new RuntimeException();
StackTraceElement[] stackTrace = ex.getStackTrace();
System.out.println(stackTrace[0]);
System.out.println(stackTrace[1]);      

Element 0 in the stackTrace array will be your constructor. Element 1 should be the location from where the constructor was invoked.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
  • I think it is worth noting, that you can also put the print part inside a loop, looping over say the first 5 Elemnts, should they exist (needs checking). That would useful, if that constructor was called inside another class's constructor to find out, where exactly that was called. – LuigiEdlCarno May 30 '13 at 08:44
0

Constructors will be called automatically at the instantiation of an Object. If you want to restrict that behavior you need to make the access modifier of the constructor to be private

MCF
  • 768
  • 2
  • 6
  • 21
0

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()
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89