将字符串转换为字符序列

Casting String to Charsequence

String 显式转换为 CharSequence 的目的是什么? String 本身实现了 CharSequence 接口。

Spring 4.x 支持 Java 6+ 并且 CharSequence 从 1.4 开始存在。

来自 Spring 框架的代码片段:

public static boolean hasText(String str) {
    // Why do we cast str to CharSequence? 
    return hasText((CharSequence) str);
}

public static boolean hasText(CharSequence str) {
    if (!hasLength(str)) {
        return false;
    }

    int strLen = str.length();
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(str.charAt(i))) {
            return true;
        }
    }
    return false;
}

这样就不会无限递归了。该方法实际上可以删除。它可能只是为了向后兼容。