在我的程序中,我使用了很多 Strings 和 StringBuilders。我想摆脱 StringBuilder toString() 方法并始终使用 CharSequences。但是我需要访问 indexOf 方法(在 StringBuilder 和 String 中都可用,但在其他实现中不可用)。我如何实现一个使该功能可见的接口?
问问题
2183 次
3 回答
3
好吧,您可以通过对已知类型的测试进行硬编码来相当容易地做到这一点,否则可以“手动”进行:
public static int indexOf(CharSequence input, String needle) {
if (input instanceof String) {
String text = (String) input;
return text.indexOf(needle);
}
if (input instanceof StringBuilder) {
StringBuilder text = (StringBuilder) input;
return text.indexOf(needle);
}
// TODO: Do this without calling toString() :)
return input.toString().indexOf(needle);
}
就硬编码类型而言,这非常难看,但它会起作用。
于 2011-08-07T12:27:50.443 回答
-1
一种想法是为每种类型创建一个具有多个静态实现的类。
public class Strings{
public static int indexOf(String input, String c){
return input.indexOf(c);
}
public static int indexOf(StringBuilder input, String c){
return input.indexOf(c);
}
public static int indexOf(YourClass input, String c){
return input.indexOf(c);
}
}
这样,您可以只调用Strings.indexOf(whatever)
具有实现的每种类型。通过让编译器/jvm 选择为您使用的方法,这将使您的代码保持干净。
于 2011-08-07T12:59:46.690 回答