Java Android获取变量名

Java Android获取变量名,java,android,variables,Java,Android,Variables,我想用log方法来帮助处理变量及其值,我想做如下操作: void log(Object object) { android.util.Log.d("TAG", "The variable " + <One way to get object name here> + " has the value " + object); } 我希望获得以下输出: The variable hits has the value 12 The variable obj has the val

我想用log方法来帮助处理变量及其值,我想做如下操作:

void log(Object object) {
    android.util.Log.d("TAG", "The variable " + <One way to get object name here> + " has the value " + object);
}
我希望获得以下输出:

The variable hits has the value 12
The variable obj has the value null
The variable s has the value nhe nhe nhem
我只需要一种方法来获取变量名,我不知道java中有什么类似的方法,但是如果有人知道一种方法来实现它

编辑

我用python做了一个很好的例子:

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)

对象变量实际上只是指向真实对象的指针,因此变量名通常只是编译成一些不可读的乱七八糟的东西

在我看来,有两种方法可以采用,一种是修改每个对象,必须有另一个包含变量名的字符串字段,然后在方法中调用getter方法


另一种可能更好的方法是将所有变量存储在HashMap中。在此数据结构中,对象与字符串配对。因此,您可以使用与其变量名相同的字符串将所有对象添加到此HashMap中,然后在另一个方法中调用HashMap的getObject key方法以查找每个对象对应的字符串。

将该方法修改为:

void log(String varName, Object object) {
    android.util.Log.d("TAG", "The variable " + varName + " has the value " + object);
}
并在调用时发送变量名

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

你不是已经得到了如图所示的名字了吗不,我想把结果说出来,我去纠正问题上的短语我正在寻找一个类似问题的解决方案。还没有运气。ps:nhe nhe nheébom demais。rachei o bico.我想要一些更友好的东西,因为在现实中,它只是日志,我不想创建一个完整的结构,您的解决方案可能会工作,但是,在我的例子中,更容易创建一个带有两个参数的日志,如:logfoo,foo;有人在给出的链接中这样说:变量的名称是编译时信息,编译后通常不会存储这些信息。如果使用调试信息编译,则会存储变量名。事实上,这不是问题,因为我只想调试。
int hits = 12;
Object obj = null;
String s = "nhe nhe nhem";
log("hits", hits);
log("obje", obje);
log("s", s);