Eclipse 默認 Debug 時鼠標懸浮變量僅顯示 toString() 內容。對於複雜對象(如含循環引用、大字段),需要自定義顯示邏輯或屏蔽敏感字段。
Window → Preferences → Java → Debug → Detail Formatters// 針對 java.util.Date 顯示格式化時間
this.getTime() + " [" + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this) + "]"
// 針對自定義 User 對象隱藏密碼
"User{id=" + this.id + ", name=" + this.name + ", email=" + this.email + "}"
// 針對 List 顯示大小與前 3 元素
"List[size=" + this.size() + ", first3=" + this.stream().limit(3).collect(java.util.stream.Collectors.toList()) + "]"
this 代表被懸浮的對象實例。String,可調用對象任意可見方法。toString(),建議用 try-catch 兜底。// 類型:com.example.entity.User
try {
return "User{id=" + this.getId()
+ ", username=" + this.getUsername()
+ ", phone=" + mask(this.getPhone())
+ ", email=" + mask(this.getEmail()) + "}";
} catch (Exception e) {
return this.toString();
}
// 輔助方法需在同類或靜態導入,此處簡化演示
String mask(String s) { return s == null ? "" : s.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); }
| 默認 toString() | 自定義 Formatter |
|---|---|
| User{id=1, username=zhang, password=123456, phone=13800001111} | User{id=1, username=zhang, phone=138****1111, email=z****@qq.com} |
Watch Expressions 監控關鍵變量變化趨勢。Inspect (Ctrl+Shift+I) 臨時評估任意表達式。Preferences → Java → Debug → Show logical structure 讓集合顯示元素而非內部節點。