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

Java 實用程式碼片段 20 選:提升開發效率的常用工具類與最佳實踐

     編輯:Java 綜合教學

Java 實用程式碼片段 20 選:提升開發效率的常用工具類與最佳實踐

日常 Java 開發中,我們反覆編寫許多通用邏輯:日期格式化、集合轉換、檔案讀寫、加密雜湊、JSON 序列化、反射操作等。本文精選 20 個高頻、生產級的程式碼片段,涵蓋字串處理、集合操作、日期時間、IO 流、加密、JSON、反射、執行緒、驗證、日誌十大場景,可直接複製整合至專案工具類,並附上關鍵注意事項與現代 API 替代建議(Java 8+ Stream、Optional、java.time、NIO.2)。

目錄速覽

  1. 字串:判空、分割、合併、Base64 編解碼
  2. 集合:List/Set/Map 互轉、去重、分組、分頁
  3. 日期:格式化、解析、計算差值、時區轉換
  4. IO:檔案讀寫、複製、目錄遍歷、資源釋放
  5. 加密:MD5、SHA-256、AES 對稱加密、RSA 非對稱
  6. JSON:物件序列化/反序列化、日期格式化、忽略 Null
  7. 反射:獲取欄位/方法、建立實例、呼叫私有方法
  8. 執行緒:安全停止、線程池提交、CompletableFuture 組合
  9. 驗證:手機、郵箱、身份證、URL 正則驗證
  10. 日誌:MDC 鏈路追蹤、參數化日誌、異常堆疊

片段展示(節選核心 5 例,完整 20 例見文末 GitHub)

1. 字串工具:null-safe 判空與合併

public class StringUtils {
    public static boolean isBlank(CharSequence cs) {
        return cs == null || cs.toString().trim().isEmpty();
    }
    
    public static String join(CharSequence delimiter, CharSequence... elements) {
        if (elements == null) return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < elements.length; i++) {
            if (i > 0) sb.append(delimiter);
            if (elements[i] != null) sb.append(elements[i]);
        }
        return sb.toString();
    }
    
    // Java 8+ 建議:String.join(",", list) / Stream.collect(Collectors.joining(","))
}

2. 集合工具:List 去重保持順序

public static  List distinctPreserveOrder(List list) {
    if (list == null) return Collections.emptyList();
    return list.stream().distinct().collect(Collectors.toCollection(LinkedList::new));
    // 或 Java 8 前:new ArrayList<>(new LinkedHashSet<>(list))
}

3. 日期工具:Java 8 java.time 最佳實踐

public class DateUtils {
    private static final DateTimeFormatter DEFAULT_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    public static String format(LocalDateTime dt, String pattern) {
        return dt == null ? "" : dt.format(DateTimeFormatter.ofPattern(pattern));
    }
    
    public static LocalDateTime parse(String str, String pattern) {
        return str == null ? null : LocalDateTime.parse(str, DateTimeFormatter.ofPattern(pattern));
    }
    
    public static long betweenDays(LocalDate start, LocalDate end) {
        return ChronoUnit.DAYS.between(start, end);
    }
    
    // 避免使用已過時的 SimpleDateFormat(非執行緒安全),改用 DateTimeFormatter(不可變、執行緒安全)
}

4. IO 工具:NIO.2 一行讀取/寫入檔案

public class FileUtils {
    public static String readFileToString(Path path, Charset charset) throws IOException {
        return Files.readString(path, charset); // Java 11+
        // Java 8: new String(Files.readAllBytes(path), charset)
    }
    
    public static void writeStringToFile(Path path, String content, Charset charset, OpenOption... options) throws IOException {
        Files.writeString(path, content, charset, options); // Java 11+
        // Java 8: Files.write(path, content.getBytes(charset), options)
    }
    
    public static void copyDirectory(Path source, Path target) throws IOException {
        Files.walkFileTree(source, new SimpleFileVisitor() {
            @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Files.createDirectories(target.resolve(source.relativize(dir)));
                return FileVisitResult.CONTINUE;
            }
            @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

5. JSON 工具:Jackson 最佳配置

public class JsonUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper()
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
        .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .setSerializationInclusion(JsonInclude.Include.NON_NULL); // 忽略 null 欄位
    
    public static String toJson(Object obj) {
        try { return MAPPER.writeValueAsString(obj); }
        catch (JsonProcessingException e) { throw new RuntimeException(e); }
    }
    
    public static  T fromJson(String json, Class clazz) {
        try { return MAPPER.readValue(json, clazz); }
        catch (IOException e) { throw new RuntimeException(e); }
    }
    
    // 針對泛型:MAPPER.readValue(json, new TypeReference>(){})
}

其餘 15 片段預覽

  • 6. Map 按 Value 排序(LinkedHashMap 保持順序)
  • 7. 集合分頁切片(`list.subList(start, end)` + 邊界檢查)
  • 8. 當前時間戳毫秒/秒/納秒獲取(`Instant.now().toEpochMilli()`)
  • 9. 檔案 MD5/SHA-256 雜湊(`MessageDigest` + 十六進制轉換)
  • 10. AES 加密/解密(CBC 模式 + PKCS5Padding + 隨機 IV)
  • 11. RSA 非對稱加密/簽名驗簽(公私鑰生成、Base64 編碼)
  • 12. 反射獲取所有欄位含父類(`getDeclaredFields` 遞迴)
  • 13. 安全停止執行緒(`interrupt()` + `isInterrupted()` 模式,拒絕 `stop()`)
  • 14. 線程池提交任務異步回調(`CompletableFuture.supplyAsync` + `thenAccept`)
  • 15. 手機號/郵箱/身份證/URL 正則驗證(預編譯 `Pattern` 重用)
  • 16. MDC 鏈路追蹤 ID 自動傳遞(`Filter` + `ThreadLocal` / `InheritableThreadLocal`)
  • 17. 參數化日誌避免字串拼接開銷(`log.debug("user={}, action={}", user, action)`)
  • 18. 異常堆疊轉字串(`StringWriter` + `PrintWriter`)
  • 19. 物件深拷貝(序列化/JSON/MapStruct/手動拷貝四種方案對比)
  • 20. 環境變數/系統屬性/配置檔統一讀取工具(優先級遞減)

完整原始碼與測試用例

所有 20 個片段的完整實作、單元測試(JUnit 5)、Maven 依賴配置已開源:

https://github.com/your-repo/java-snippets-20

使用建議

  1. 複製即用:將需求片段複製至專案 `util` 套件,依賴對應庫(Jackson、Apache Commons Lang3、Guava 等)。
  2. 優先現代 API:Java 8+ 專案請優先使用 `java.time`、`Stream`、`Optional`、`CompletableFuture`、`NIO.2`,避免舊 API 坑點。
  3. 單元測試覆蓋:每個工具方法至少覆蓋正常、邊界、空值、異常四類測試案例。
  4. 定期重構:隨 JDK 版本升級,替換過時 API(如 `SimpleDateFormat` → `DateTimeFormatter`)。

掌握這 20 類高頻片段,能讓你在日常開發中少寫樣板碼、避開常見坑、專注業務邏輯,顯著提升編碼效率與程式碼品質。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved