如何创建String类副本? [英] How to create a String class replica?
问题描述
我需要使用与 java.lang.String
完全相同的方法创建一个类。
I need to create a class with exactly the same methods as java.lang.String
.
什么在Java中这是最好的方法吗?
What is the best way to do this in Java?
我知道我不能扩展String类,因为它是 final
。我不是在寻找需要复制 java.lang.String
源代码的解决方案。例如,假设我在我的自定义类 MyString
中需要功能 length()
,它具有相应的' myLength()`方法。
I know that I can't extend String class as it is final
. I am not looking at solutions where I need to copy the source code of java.lang.String
. For example, assume that I need the functionality length()
within my custom class named MyString
, which has a corresponding 'myLength()` method.
实现 myLength()
的最佳方式是什么?
What is the best way to implement myLength()
?
我不是在寻找各种算法来找出字符串的长度,而是重用字符串
的 length()
方法。现在,一旦我准备好 MyString
类,我就可以在任何地方使用它进行自定义操作。
I am not looking at various algorithms to find out the length of a string but to reuse String
's length()
method. Now once I have MyString
class ready, I should be able to use it anywhere for my custom manipulations.
推荐答案
从您的问题来看,您所寻找的事情很简单委托:
From your question it sounds like the thing you are looking for is simple delegation:
class MyString {
String delegate; // The actual string you delegate to from your class
public MyString(String delegate) {
this.delegate = delegate; // Assign the string that backs your class
}
int length() {
return delegate.length(); // Delegate the method call to the string
}
// other methods that delegate to the string field
}
这篇关于如何创建String类副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!