That's.. not how it works. You have a fundamental misunderstanding of how java works. In:
Object name = new Object();
you did not just create a new object named name
. No, you did 3 completely seperate things:
You made a variable, of type Object, with name name
. This is like a blank piece of paper that you can paint treasure maps on. That's the Object name;
part.
You made a new object. (The new Object()
part). It has no name. It is like creating a new treasure chest, and burying it in the sand.
You have drawn on your treasure map, the route to the treasure you just buried (that's the =
in the middle part).
You can now tear up your treasure map (name = null
- there, wiped out the map!), but the treasure is still there, buried in the sand. If there are no other treasure maps in existence where X marks that treasure, eventually the garbage collector will dig it and get rid of it.
In other words, objects can exist where no variables are pointing at it.
You can also make more treasure maps and copy the reference:
Object name = new Object();
Object otherName = name;
Now you have 1 treasure (new Object()
, with no name, and 2 treasure maps (name
and otherName
) that currently have drawn maps on them going to that treasure. But you can change that:
Object name = new Object();
Object otherName = name;
name = someOtherObject;
now the name of the map that originally had a map to this object on it, now has a map to some completely different treasure on it.
Your question is: How can I ask the treasure about the name of the map that points at it. Hopefully this explanation makes it clear as to why this is not possible at all, and java does not let you do this, in any way.