2

What is the purpose of casting String to CharSequence explicitly? String itself implements CharSequence interface.

Spring 4.x supports Java 6+ and CharSequence is present since 1.4.

Code snippet from Spring Framework:

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;
}
5
  • 12
    So that it won't recurse infinitely. The method could actually be removed. It is probably only there for backwards compatibility. Commented Jun 27, 2017 at 7:58
  • kind of tricky method overloading... Commented Jun 27, 2017 at 7:59
  • 1
    @EJP, oh..so we do it to point compiler that we want to execute method specific to CharSequence parameter. Thank you. Commented Jun 27, 2017 at 7:59
  • @EJP this is the right answer. You should post it so that it can be accepted. Commented Jun 27, 2017 at 8:04
  • @ArnaudDenoyelle I do agree Commented Jun 27, 2017 at 8:05

1 Answer 1

5

So that it won't recurse infinitely. The method could actually be removed. It is probably only there for backwards compatibility.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.