Determining an object's variable name dynamically?
- by ZenBlender
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!