假設我有以下介面:
public interface NUMS {
public static final int ZERO = 0;
public static final int ONE = 1;
public static final int TWO = 2;
}
然后我有一個回傳 0-2 之間 int 的函式。是否有任何選項可以獲取該數字在介面中代表的成員名稱?
前任:
函式回傳 1,我想將它映射回 ONE,而不使用 Map/Array。
謝謝!
uj5u.com熱心網友回復:
從技術上講,使用反射:
String getConstantName(int value) {
// use reflection to check all fields of NUMS
for (Field f : NUMS.class.getFields()) {
try {
if (f.getInt(null) == value) {
return f.getName();
}
} catch (IllegalAccessException e) {
// ignore
}
}
return "";
}
但這只是為了教育目的,請不要在實際代碼中使用這樣的方法。正如其他人建議的那樣,只需使用enum.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341701.html
上一篇:無需格式化程式將時間戳轉換為字串
