I am looking to add a function to a program where I use static variables to create a list of all the times the driver has used the constructor, using names. What I need to know is this, is there a way, in java, to access what the reference variable is (as a string) to add it to the list? Pseudocode:
public ClassName
String static list = "";
Public ClassName (parameters){
list += getReferenceVariable();
}
The getReferenceVariable is what I'm asking if anyone knows a way to do that
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
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments