支持它的 CharSequence 实现上的 indexOf
在我的程序中,我使用了大量的字符串和字符串构建器。我想摆脱 StringBuilder toString() 方法并在整个过程中使用 CharSequences。但是,我需要访问 indexOf 方法(该方法在 StringBuilder 和 String 中都可用,但在其他实现中不可用)。我如何实现一个使该函数可见的接口?
In my program I use a lot of Strings and StringBuilders. I would like to get rid of the StringBuilder toString() method and use CharSequences throughout. However I need access to the indexOf method (which is available in both StringBuilder and String but not in other implementations). How might I implement an interface that will make this function visible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,您可以通过对已知类型进行硬编码测试来相当轻松地完成此操作,否则“手动”执行此操作:
就硬编码类型而言,这非常难看,但它会起作用。
Well, you could do it reasonably easily by hardcoding tests for known types, and doing it "manually" otherwise:
This is pretty ugly in terms of hard-coding the types, but it'll work.
您可以使用 TextUtils 中的默认方法: indexOf
You can use the default method from TextUtils: indexOf
一种想法是为每种类型创建一个具有多个静态实现的类。
这样,您只需为每个具有实现的类型调用 Strings.indexOf(whatever) 即可。通过让编译器/jvm 选择为您使用的方法,这将使您的代码保持干净。
One thought is to have a class with multiple static implementations for each type.
This way, you can just call
Strings.indexOf(whatever)
for each type that has an implementation. Which will keep your code clean by letting the compiler/jvm pick which method to use for you.