CaseFormat

guava-librariesのCaseFormatというenumを見ていました。

キャメルケースとかハイフン区切りとか大文字小文字とか、文字列の書式を表す列挙のようです。

「helloWorld」を「HELLO_WORLD」に変換してくれる「to」というメソッドが提供されていました。

    LOWER_CAMEL.to(UPPER_UNDERSCORE, "helloWorld")); // HELLO_WORLD

エンティティのクラス名からテーブル名に変換するのに使えそうです。

テスト

package com.google.common.base;

import static com.google.common.base.CaseFormat.*;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class CaseFormatTest {

  @Test
  public void testValues() {
    List<CaseFormat> actual = Arrays.asList(CaseFormat.values());
    assertEquals(Arrays.asList(
        LOWER_HYPHEN,        // 小文字 ハイフン区切り
        LOWER_UNDERSCORE,    // 小文字 アンダースコア区切り
        LOWER_CAMEL,         // 小文字で始まるキャメルケース
        UPPER_CAMEL,         // 大文字で始まるキャメルケース
        UPPER_UNDERSCORE     // 大文字 アンダースコア区切り
    ), actual);
  }

  @Test
  public void testTo() {
    String word = "hello-world";
    assertEquals("hello_world", LOWER_HYPHEN.to(LOWER_UNDERSCORE, word));
    assertEquals("helloWorld" , LOWER_HYPHEN.to(LOWER_CAMEL     , word));
    assertEquals("HelloWorld" , LOWER_HYPHEN.to(UPPER_CAMEL     , word));
    assertEquals("HELLO_WORLD", LOWER_HYPHEN.to(UPPER_UNDERSCORE, word));
    
    word = "hello_world";
    assertEquals("hello-world", LOWER_UNDERSCORE.to(LOWER_HYPHEN    , word));
    assertEquals("helloWorld" , LOWER_UNDERSCORE.to(LOWER_CAMEL     , word));
    assertEquals("HelloWorld" , LOWER_UNDERSCORE.to(UPPER_CAMEL     , word));
    assertEquals("HELLO_WORLD", LOWER_UNDERSCORE.to(UPPER_UNDERSCORE, word));
    
    word = "helloWorld";
    assertEquals("hello-world", LOWER_CAMEL.to(LOWER_HYPHEN    , word));
    assertEquals("hello_world", LOWER_CAMEL.to(LOWER_UNDERSCORE, word));
    assertEquals("HelloWorld" , LOWER_CAMEL.to(UPPER_CAMEL     , word));
    assertEquals("HELLO_WORLD", LOWER_CAMEL.to(UPPER_UNDERSCORE, word));
    
    word = "HelloWorld";
    assertEquals("hello-world", UPPER_CAMEL.to(LOWER_HYPHEN    , word));
    assertEquals("hello_world", UPPER_CAMEL.to(LOWER_UNDERSCORE, word));
    assertEquals("helloWorld" , UPPER_CAMEL.to(LOWER_CAMEL     , word));
    assertEquals("HELLO_WORLD", UPPER_CAMEL.to(UPPER_UNDERSCORE, word));
    
    word = "HELLO_WORLD";
    assertEquals("hello-world", UPPER_UNDERSCORE.to(LOWER_HYPHEN    , word));
    assertEquals("hello_world", UPPER_UNDERSCORE.to(LOWER_UNDERSCORE, word));
    assertEquals("helloWorld" , UPPER_UNDERSCORE.to(LOWER_CAMEL     , word));
    assertEquals("HelloWorld" , UPPER_UNDERSCORE.to(UPPER_CAMEL     , word));
    
  }

}