Guava CaseFormat


概述

CaseFormat用來轉換各種不同的編程語言間的變量名命名格式, 主要用到的方法只有一個 CaseFormat.to(CaseFormat from, String s)

        CaseFormat fromFormat = CaseFormat.LOWER_CAMEL;
        CaseFormat toFormat = CaseFormat.UPPER_CAMEL;
        String s = "lowerCamel";
        System.out.println(fromFormat.to(toFormat, s));

輸出

lowerCamel
LowerCamel

 

代碼分析

package com.google.common.base;

import com.google.common.annotations.GwtCompatible;

/**
* Utility class for converting between various ASCII case formats.
* 轉換ASCII字符串各種格式的工具類
*
* @author Mike Bostock
* @since 1.0
*/
@GwtCompatible
public enum CaseFormat {
    /**
     * Hyphenated variable naming convention, e.g., "lower-hyphen".
     * 帶連接符的變量名轉換
     */
    LOWER_HYPHEN(CharMatcher.is('-'), "-"),

    /**
     * C++ variable naming convention, e.g., "lower_underscore".
     * C++ 變量名轉換
     */
    LOWER_UNDERSCORE(CharMatcher.is('_'), "_"),

    /**
     * Java variable naming convention, e.g., "lowerCamel".
     * Java 變量名轉換
     */
    LOWER_CAMEL(CharMatcher.inRange('A', 'Z'), ""),

    /**
     * Java and C++ class naming convention, e.g., "UpperCamel".
     * Java 和 C++ 類名轉換
     */
    UPPER_CAMEL(CharMatcher.inRange('A', 'Z'), ""),

    /**
     * Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE".
     * Java 和 C++ 常量命名轉換
     */
    UPPER_UNDERSCORE(CharMatcher.is('_'), "_");

    private final CharMatcher wordBoundary;
    private final String wordSeparator;

    CaseFormat(CharMatcher wordBoundary, String wordSeparator) {
        this.wordBoundary = wordBoundary;
        this.wordSeparator = wordSeparator;
    }

    /**
     * Converts the specified {@code String s} from this format to the specified {@code format}. A
     * "best effort" approach is taken; if {@code s} does not conform to the assumed format, then the
     * behavior of this method is undefined but we make a reasonable effort at converting anyway.
     *
     * 使用這個format將指定String s轉為指定format.采取的是"盡力而為"的方法;假如s不符合設定的格式
     * 那么這個方法的行為將會是不確定的,但我們會盡量做出合理的轉換
     *
     * 實際上我們使用的只有這一個方法
     */
    public String to(CaseFormat format, String s) {
        if (format == null) {
            throw new NullPointerException();
        }
        if (s == null) {
            throw new NullPointerException();
        }

        if (format == this) {
            return s;
        }

        /* optimize cases where no camel conversion is required */
        /* 沒有駝峰轉換的時候優化轉換 */
        switch (this) {
            case LOWER_HYPHEN:
                switch (format) {
                    case LOWER_UNDERSCORE:
                        return s.replace('-', '_');
                    case UPPER_UNDERSCORE:
                        return Ascii.toUpperCase(s.replace('-', '_'));
                }
                break;
            case LOWER_UNDERSCORE:
                switch (format) {
                    case LOWER_HYPHEN:
                        return s.replace('_', '-');
                    case UPPER_UNDERSCORE:
                        return Ascii.toUpperCase(s);
                }
                break;
            case UPPER_UNDERSCORE:
                switch (format) {
                    case LOWER_HYPHEN:
                        return Ascii.toLowerCase(s.replace('_', '-'));
                    case LOWER_UNDERSCORE:
                        return Ascii.toLowerCase(s);
                }
                break;
        }

        // otherwise, deal with camel conversion
        // 處理駝峰轉其他的轉換
        StringBuilder out = null;
        int i = 0;
        int j = -1;
        // 將字符串按分隔符切分單詞,轉換每個單詞
        while ((j = wordBoundary.indexIn(s, ++j)) != -1) {
            if (i == 0) {
                // include some extra space for separators
                // 為分隔符留出額外的空間
                out = new StringBuilder(s.length() + 4 * wordSeparator.length());
                // 第一個單詞使用normalizeFirstWord處理
                out.append(format.normalizeFirstWord(s.substring(i, j)));
            } else {
                // 后續單詞用normalizeWord處理
                out.append(format.normalizeWord(s.substring(i, j)));
            }
            out.append(format.wordSeparator);
            // 當前坐標后移
            i = j + wordSeparator.length();
        }
        if (i == 0) {
            return format.normalizeFirstWord(s);
        }
        // 處理最后一個分隔符右邊的字符串
        out.append(format.normalizeWord(s.substring(i)));
        return out.toString();
    }

    /**
     * 將第一個單詞普通化
     * LOWER_CAMEL -> 全小寫
     * 其他 -> normalizeWord
     */
    private String normalizeFirstWord(String word) {
        switch (this) {
            case LOWER_CAMEL:
                return Ascii.toLowerCase(word);
            default:
                return normalizeWord(word);
        }
    }

    /**
     * 將單詞普通化
     * LOWER_HYPHEN, LOWER_UNDERSCORE -> 全小寫
     * LOWER_CAMEL, UPPER_CAMEL -> 第一個字母大寫其他字母小寫
     * UPPER_UNDERSCORE -> 全大寫
     */
    private String normalizeWord(String word) {
        switch (this) {
            case LOWER_HYPHEN:
                return Ascii.toLowerCase(word);
            case LOWER_UNDERSCORE:
                return Ascii.toLowerCase(word);
            case LOWER_CAMEL:
                return firstCharOnlyToUpper(word);
            case UPPER_CAMEL:
                return firstCharOnlyToUpper(word);
            case UPPER_UNDERSCORE:
                return Ascii.toUpperCase(word);
        }
        throw new RuntimeException("unknown case: " + this);
    }

    /**
     * 將單詞第一個字母變大寫,其他變小寫
     */
    private static String firstCharOnlyToUpper(String word) {
        int length = word.length();
        if (length == 0) {
            return word;
        }
        return new StringBuilder(length)
                .append(Ascii.toUpperCase(word.charAt(0)))
                .append(Ascii.toLowerCase(word.substring(1)))
                .toString();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM