Let us say that I want to create a class MyString
which is a wrapper for java.lang.String
. I have added a new method called reverse
.
public class MyString {
private String text=null;
public MyString(String foo){
text=foo;
}
public String reverse(){
// implementation omitted
return reversedString;
}
}
Now String
is final. Therefore I cannot extend it. One way to have MyString
support all methods that String
supports is by providing wrapper method implementations such as the method toCharArray()
:
public char[] toCharArray(){
// redirect to String member field 'text'
return text.toCharArray();
}
Is there a way I can redirect method calls to the member field without actually having to code the wrapper implementation? Something similar to super?
Edit 1: This is not part of the question but I invite comments towards this.
A nice-to-have feature in java would be some way of delegating methods to inner fields. Something like:
public class MyString delegatesTo String{
private String text=null;
public MyString(String foo){
text=foo;
delegateTo(text);
// delegateTo is implemented in Object.java or in the jvm.
// Not invoking the delegateTo method in the constructor will raise a compiler
// error since the class is supposed to "delegateTo" a String.
// The instance of text could become immutable after it is assigned as the "delegatee".
}
}