If I understand you correctly, you want to keep a list of all the times the constructor was called, and save the names of the currently-being-created variable? Because the "Reference variable" is none when you use the constructor, since you call the constructor with a new MyClass()
, and not some obj.MyClass()
.
If, however, you simply want to know who called you (As a stack trace is), you can simply, as written in this thread (no pun intended), use
Thread.currentThread().getStackTrace()
, and then choose the desired stack frame (Probably 2, since The first element (index 0) in the array is the java.lang.Thread.getStackTrace method, the second (index 1) is the constructor, and 2 is where the constructor was called from), where you can get (for example) the name of the source file that this stack trace corresponds to. Documentation of getFileName()
Since I haven't tried it on my end (not possible at the moment), I give you code to use with caution:
public class MyClass(){
MyClass(){
callerName = Thread.currentThread().getStackTrace()[2].getFileName();
... // anything here
}
}