首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Eclipse Debug 變量懸浮提示自定義:打造專屬調試視圖

     編輯:Java 綜合教學

需求背景

Eclipse 默認 Debug 時鼠標懸浮變量僅顯示 toString() 內容。對於複雜對象(如含循環引用、大字段),需要自定義顯示邏輯或屏蔽敏感字段。

配置入口

  1. Window → Preferences → Java → Debug → Detail Formatters
  2. 點擊 New... 添加類型格式化器

Detail Formatter 編寫規則

// 針對 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,可調用對象任意可見方法。
  • 異常拋出時 Eclipse 會回退到默認 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}

調試效率提升清單

  1. 為常用實體類、集合、日期配置 Formatter,減少展開對象樹操作。
  2. 配合 Watch Expressions 監控關鍵變量變化趨勢。
  3. 使用 Inspect (Ctrl+Shift+I) 臨時評估任意表達式。
  4. 開啟 Preferences → Java → Debug → Show logical structure 讓集合顯示元素而非內部節點。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved