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;
}