【发布时间】:2015-01-27 09:18:04
【问题描述】:
我想做一个日志方法来帮助处理变量及其值,我想做类似的事情:
void log(Object object) {
android.util.Log.d("TAG", "The variable " + <One way to get object name here> + " has the value " + object);
}
当我运行这样的事情时:
int hits = 12;
Object obj = null;
String s = "nhe nhe nhem";
log(hits);
log(obje);
log(s);
我想得到以下输出:
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)
【问题讨论】:
-
你不是已经得到了如图所示的名字吗..
-
不,我想得到那个输出,我去纠正问题中的短语
-
我正在寻找类似问题的解决方案。还没有运气。 ps:“nhe nhe nhem”é bom demais。 rachei o bico。