简体   繁体   中英

Accesing a reference variable from inside a method java

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM