簡體   English   中英

Android獲取變量名

[英]Android get variable name

我想做一個日志方法來幫助變量及其值,我想做些類似的事情:

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 <Object,String>中。 在此數據結構中,對象與字符串配對。 因此,您需要使用與其變量名相同的字符串將所有對象添加到此HashMap中,然后在另一個方法中調用哈希圖的get(Object 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM