简体   繁体   English

从方法内部访问参考变量

[英]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? 我需要知道的是,在java中,是否有一种方法可以访问引用变量(作为字符串)并将其添加到列表中? 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 我要问的是getReferenceVariable,是否有人知道这样做的方法

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() . 因为在使用构造函数时“参考变量”为none,所以使用new MyClass()而不是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. 但是,如果您只是想知道谁打了您(如堆栈跟踪所示),则可以按照此线程中的描述 (无双关语)简单地使用Thread.currentThread().getStackTrace() ,然后选择所需的堆栈框架(可能为2,因为数组中的第一个元素(索引0)是java.lang.Thread.getStackTrace方法,第二个元素(索引1)是构造函数,而2是调用构造函数的位置),您可以在其中获取(例如)此堆栈跟踪所对应的源文件的名称。 Documentation of getFileName() 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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