2

I want do a log method to help with variables and their values, I want to do something like:

void log(Object object) {
    android.util.Log.d("TAG", "The variable " + <One way to get object name here> + " has the value " + object);
}

and when I run something like this:

int hits = 12;
Object obj = null;
String s = "nhe nhe nhem";
log(hits);
log(obje);
log(s);

I want to get the following output:

The variable hits has the value 12
The variable obj has the value null
The variable s has the value nhe nhe nhem

I just need one way to get the variable name, I don't know anything similar in java, but if anyone knows one way to do it....


EDIT

I did an example in python that works fine:

myVariableWithSomeFooName = 32

for key, value in list(locals().iteritems()):
    if id(value) == id(myVariableWithSomeFooName):
        itemName = key

print "The " + str(itemName) + " has the value " + str(myVariableWithSomeFooName)
Stefano Zanini
  • 5,876
  • 2
  • 13
  • 33
ademar111190
  • 14,215
  • 14
  • 85
  • 114

2 Answers2

0

Object variables are actually just pointers to the real object, so the variable name generally is just compiled to be some unreadable mess.

Off the top of my head, there are two approaches you could take, one would be to modify each object you have to have another String field that contains the variable name, and then a getter method could be called in your method.

Another (probably better) way could be to store all of your variables in a HashMap < Object, String >. In this data structure the object is paired with a string. So you would add all of your objects to this HashMap with a string that is the same as its variable name, then in your other method call the hashmap's get(Object key) method to find the string that goes with each object.

Ben Marshall
  • 171
  • 2
  • 12
  • I want something more friendly because in real it is just to logs, i dont want create a entire structure, your solutions probably works, but, in my case is more easy create a log with two parameter like: `log("foo", foo);` – ademar111190 Nov 28 '14 at 18:47
0

Modify the method to this:

void log(String varName, Object object) {
    android.util.Log.d("TAG", "The variable " + varName + " has the value " + object);
}

and send the variable name when calling

int hits = 12;
Object obj = null;
String s = "nhe nhe nhem";
log("hits", hits);
log("obje", obje);
log("s", s);
Anupam Basak
  • 1,503
  • 11
  • 13
  • http://stackoverflow.com/questions/3959206/how-do-i-print-the-variable-name-holding-an-object __Someone told this in the link given:__ The name of the variable is compile time information that is not typically stored after compilation. The variable name is stored if you compile with debugging information. – Anupam Basak Nov 28 '14 at 19:04
  • in truth it is not a problem because I want only to debug. – ademar111190 Nov 28 '14 at 19:08