mcpField
C
commons-patterns

commons-patterns

github.com/full-stack-skills開発785 回インストール5 週間前に更新
リポジトリ

commons-patterns について

commons-patterns は、Apache Commons を使う Java 開発者向けの利用パターン集です。Lang3、IO、Collections4 の API の意味や移行時の注意点、よくある落とし穴をまとめています。

主な機能

  1. 01StringUtils の空判定の使い分け
  2. 02Commons IO のファイル・ストリーム操作
  3. 03Collections4 の集合演算
  4. 04ランダム文字列生成と引数検証
  5. 05Lang3 の移行時の注意点

活用シーン

  1. 01空文字と空白文字の区別
  2. 02大きなファイルの行単位処理
  3. 03引数の検証追加
  4. 04確認コードやトークンの生成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/full-stack-skills/java-skills --skill commons-patterns

インストール後、Claude Code で/commons-patternsを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

agents/
openai.yaml
examples/
commons-realworld.md
references/
commons-resources.md

詳細

Apache Commons ベストプラクティスパターン

出典:Commons Home | Lang3 User Guide | IO Description

対応範囲

✅ 得意分野
  1. StringUtils の空判定パターン — isEmpty、isBlank、defaultString の厳密な意味に基づく選択
  2. Commons IO のファイル操作 — FileUtils による読み書き・コピー/IOUtils によるストリーム操作/LineIterator による行単位の処理
  3. Commons Collections4 — CollectionUtils/MultiValuedMap/MapUtils
  4. RandomStringUtils — ランダム文字列の生成(認証コード/Token/一時パスワード)
  5. Validate — パラメーターの検証(3.0以降はIllegalArgumentExceptionではなくNullPointerExceptionがスローされる点に注意)
❌ 対象外
  1. 中国語固有の機能(身分証明書番号/ピンイン) → hutool-patterns
  2. 不変コレクション/キャッシュ/EventBus → guava-patterns
  3. Beanマッピング/JSON → mapstruct-patterns/jackson-patterns

Commons/Guava/Hutool の選択表

シナリオCommonsGuavaHutool優先選択
文字列の空判定/切り詰め/埋め込み⭐⭐⭐⭐⭐⭐⭐⭐任意(チームの規約に従う)
ファイルのコピー/削除/行読み込み⭐⭐⭐⭐⭐⭐Commons IO
ファイル名/パスの処理⭐⭐⭐—⭐⭐Commons IO
集合演算(積/和/差)⭐⭐⭐⭐⭐⭐⭐⭐⭐任意
日付処理(旧Date)⭐—⭐⭐⭐Java8 Time
ランダム文字列⭐⭐⭐—⭐⭐Commons Lang3
HTML/XMLのエスケープ⭐⭐⭐—⭐Commons Lang3
数学/統計⭐⭐⭐—⭐Commons Math

コアパターン

パターン 1: StringUtils の厳密な空判定
// ✅ isEmpty: null 或 "" → true (不含空格)
StringUtils.isEmpty(null);    // true
StringUtils.isEmpty("");      // true
StringUtils.isEmpty(" ");     // false ← 注意!
StringUtils.isEmpty("abc");   // false

// ✅ isBlank: null 或 空白字符 → true
StringUtils.isBlank(null);    // true
StringUtils.isBlank("");      // true
StringUtils.isBlank(" ");     // true ← 含空格也true
StringUtils.isBlank("abc");   // false

// ✅ 选择规则: 表单验证用isBlank(不接受空白输入),集合判空用isEmpty

// ✅ defaultString: null安全取值
StringUtils.defaultString(str, "");         // null → ""
StringUtils.defaultIfBlank(str, "N/A");     // null/""/" " → "N/A"

// ✅ 填充与截断
StringUtils.leftPad("1", 3, '0');           // "001"
StringUtils.abbreviate("very long text", 10); // "very lo..."
パターン 2: Commons IO のファイルパターン
// ✅ 读取整个文件(小文件,<10MB)
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8);

// ✅ 逐行读(大文件) — LineIterator 模式
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try { while (it.hasNext()) { String line = it.nextLine(); /* 处理 */ }
} finally { LineIterator.closeQuietly(it); }

// ✅ 流操作(需手动关流)
InputStream in = new URL("https://example.com").openStream();
try { String result = IOUtils.toString(in, StandardCharsets.UTF_8); }
finally { IOUtils.closeQuietly(in); }

// ❌ 反模式: IOUtils.toString() 读 1GB 文件 → 尝试创建1GB String → OOM

// ✅ 写入/复制/删除
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
FileUtils.copyFile(src, dest);
FileUtils.forceMkdir(dir);          // 递归创建目录
FileUtils.deleteDirectory(dir);      // 递归删除

// ✅ 文件名处理
FilenameUtils.getExtension("archive.tar.gz");  // "gz" (最后一个.)
FilenameUtils.getBaseName("/path/file.txt");   // "file"
String normalized = FilenameUtils.normalize("C:/a/../b/file.txt"); // "C:/b/file.txt"
パターン 3: Commons Lang3 の移行時の注意点
// ❌ 旧包名 — 不要用
import org.apache.commons.lang.StringUtils;

// ✅ 新包名(3.0+) — 必须用
import org.apache.commons.lang3.StringUtils;

// Maven坐标
// groupId: commons-lang → org.apache.commons
// artifactId: commons-lang → commons-lang3
パターン 4: Validate によるパラメーター検証
// ⚠️ Commons Lang 3.0 变化: Validate 校验 null 抛 NullPointerException
// (对齐JDK标准行为,以前抛 IllegalArgumentException)
Validate.notNull(obj, "参数不能为空: %s", name);   // 抛 NPE
Validate.isTrue(age > 0, "年龄必须>0");             // 抛 IllegalArgumentException
// 注意:验证null用Validate.notNull,验证状态用Validate.isTrue
パターン 5: RandomStringUtils
// ✅ 随机字母数字(验证码/Token)
RandomStringUtils.randomAlphanumeric(6);      // "a3Bx9K"
RandomStringUtils.randomAlphanumeric(32);     // 32位Token
// ✅ 随机数字
RandomStringUtils.randomNumeric(6);           // "482931"
// ✅ 随机字母
RandomStringUtils.randomAlphabetic(8);        // "AbCdEfGh"
パターン 6: 集合演算
// ⚠️ 包名: org.apache.commons.collections4 (不是 collections)
CollectionUtils.isEmpty(coll);
CollectionUtils.union(list1, list2);          // 并集
CollectionUtils.intersection(list1, list2);   // 交集
CollectionUtils.subtract(list1, list2);       // 差集(list1 - list2)

MapUtils.getString(map, "key", "default");    // null安全取值

注意点

  1. isEmpty と isBlank の違い — isEmpty(" ")→true(空白を含まない)、isBlank(" ")→true(空白を含む)
  2. IOUtils.toString はストリーム全体をメモリに読み込む — 大きなファイル(>10MB)はLineIteratorで1行ずつ読み込む
  3. IOUtils.toString はストリームを閉じない — finally { IOUtils.closeQuietly(in) } と組み合わせる
  4. Lang3 DateUtils は Java8 LocalDateTime と互換性がない — java.time APIを使い、Commonsは旧Dateのみに使用する
  5. Collections4 のパッケージ名は collections4 — collections ではない(こちらは3.x)
  6. Lang3 3.0以降では isAlpha/isNumeric/isAlphanumeric("")→false — 以前のバージョンではtrueを返す
  7. Maven座標: groupId=org.apache.commons, artifactId=commons-lang3 — commons-lang ではない
  8. Validate.notNull は NullPointerException をスローする — Validate.isTrue は IllegalArgumentException をスローする

データプライバシー

このスキルはユーザーデータを収集、保存、または送信しません。

コメント