0

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

  • Every object has a `toString()` method, and every raw type can be transformed to a String representation. Is that what you mean? Can you provide pseudo code of what you're trying to do? – Andrew S Nov 29 '17 at 14:22
  • Please provide *actual* code rather than pseudo-code. It's very hard to help when we can only see pseudo-code. – Jon Skeet Nov 29 '17 at 16:46
  • Yes, I have provided some pseudocode (for clarification) – Peregrine Lennert Nov 29 '17 at 16:47
  • 1
    It's not clear what you mean by "the reference variable as a string" to start with - and using *real* code instead of pseudo-code would be much, much better. If you mean getting the `x` name out of `Foo x = new Foo()` from within the `Foo` constructor then no, you absolutely can't. – Jon Skeet Nov 29 '17 at 16:53
  • Ok thank you Jon, that's what I was trying to ask. I shall learn to format my questions better. – Peregrine Lennert Nov 29 '17 at 16:57

1 Answers1

0

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
    }
}
Zionsof
  • 1,196
  • 11
  • 23