Java Android获取变量名
我想用log方法来帮助处理变量及其值,我想做如下操作: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
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