Determining an object's variable name dynamically?

Posted by ZenBlender on Stack Overflow See other posts from Stack Overflow or by ZenBlender
Published on 2010-05-09T15:03:05Z Indexed on 2010/05/09 15:08 UTC
Read the original article Hit count: 159

Filed under:
|

Let's say I have some objects:

ArrayList<SomeObject> list = new ArrayList<SomeObject>();
SomeObject A = new SomeObject();
SomeObject B = new SomeObject();
SomeObject C = new SomeObject();
SomeObject D = new SomeObject();

These constructors automatically add each object to the ArrayList so I can iterate over them but still maintain the variable names for direct access:

public SomeObject(){
   // init stuff here
   list.add(this);
}

But then, let's say I want to output some debug info, and iterate through list and print out the NAME of each object? How can I do that? Essentially, when "SomeObject A = new SomeObject();" is executed, I want to use reflection (if possible) to determine that this variable's name is "A" (a String) and either store that in the object when the constructor executes, or determine it dynamically through reflection when referencing this object with the variable named "A". Does that make sense? How can I do this?

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about reflection