Delfino
Delfino

Reputation: 1009

Object Instance Manipulation

If I have an Object instance, say a4, is there a way I could print out the name of the instance?

So with the instance a4, I would like my output to say a4.

Upvotes: 0

Views: 134

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533530

The simple answer is; if you want an object to have a name, give it a name field and add this field to the toString()


Local variables are only available in the debug information of a method. It is possible to read the byte code of a method and reverse engineer a name but this requires an extraordinary amount of work.

Consider

Object a1 = ...
Object b1 = a1;

The same object is referenced by two local variables. An object can be referenced in any number of places. e.g the empty string object is often the most referenced object in a Java program. It can appear in 10Ks places in a normal program.


I'm trying to add an array to a HashMap using a method that is only passed in a HashMap key. I take the key, extract an array already in the HashMap, make a clone of it, and then place that clone in the HashMap using the name of the instance as the key.

Say you pass an array into a method like

public void addArray(int... array) {

At this point the "name" of the reference to the array is array and it will not be anything difference.

What you need is to pass the name you want the array to have as there is no way for a caller to know what the callee used as a local variable. Often a variable has no name in the first place.

addArray(1, 2, 3);

or

addArray(calculateNumbers());

or

int[] nums = { 1, 2, 3 };
addArray(nums);

Note: nums is not actually needed as a local variable can be optimised away. i.e. There is a good chance nums won't even exist at runtime.


What you need to do is

public void addArray(String name, int... array) {
    map.put(name, array);
}

Upvotes: 0

JamesENL
JamesENL

Reputation: 6540

Not stalking you I swear!

Short answer: No

Long Answer: Its impossible to get the name of a local variable using the reflection API as it is simply not available to the JVM. Have a look here: Java Reflection: How to get the name of a variable?

Its a hideously messy thing to attempt to do. Why are you trying to do it?

Upvotes: 1

Related Questions