我想做一个日志方法来帮助变量及其值,我想做些类似的事情:
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)
最佳答案
对象变量实际上只是指向实际对象的指针,因此通常将变量名编译为难以理解的混乱。
在我头顶上,您可以采取两种方法,一种是修改每个对象,而必须拥有一个包含变量名称的另一个String字段,然后可以在您的方法中调用getter方法。
另一种(可能更好)的方法可能是将所有变量存储在HashMap 中。在此数据结构中,对象与字符串配对。因此,您将使用与其变量名相同的字符串将所有对象添加到此HashMap中,然后在另一个方法中调用哈希图的get(Object key)方法以查找每个对象附带的字符串。