【发布时间】:2011-08-07 12:24:07
【问题描述】:
在我的程序中,我使用了很多字符串和字符串构建器。我想摆脱 StringBuilder toString() 方法并始终使用 CharSequences。但是我需要访问 indexOf 方法(在 StringBuilder 和 String 中都可用,但在其他实现中不可用)。我应该如何实现一个可以使这个函数可见的接口?
【问题讨论】:
在我的程序中,我使用了很多字符串和字符串构建器。我想摆脱 StringBuilder toString() 方法并始终使用 CharSequences。但是我需要访问 indexOf 方法(在 StringBuilder 和 String 中都可用,但在其他实现中不可用)。我应该如何实现一个可以使这个函数可见的接口?
【问题讨论】:
好吧,您可以通过对已知类型的测试进行硬编码来相当容易地做到这一点,否则可以“手动”完成:
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);
}
就类型的硬编码而言,这非常难看,但它会起作用。
【讨论】:
一种想法是为每个类型创建一个具有多个静态实现的类。
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 选择为您使用的方法,这将使您的代码保持干净。
【讨论】:
input 有YourClass 类型,并且没有indexOf(),这有什么帮助(第三种情况)?