Is there an equivalent of super for redirecting method calls to inner fields in wrapper classes

StackOverflow https://stackoverflow.com/questions/1603291

  •  05-07-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

No, this cannot be done directly.

You could define an interface containing all java.lang.String methods (plus your methods) and implement it with a dynamic proxy redirecting to the string implementation (with all the negative implications of dynamic proxies).

Probably you're better of with a type conversion new MyString(string).reverse() unfortunately Java does not have C#'s extension methods or Scala's implicit type conversions.

There are of course plenty of reverse implementations, for example from the apache commons library. It is implemented in a procedural style:

String reversed = StringUtils.reverse(string);

(I think your reverse method should return MyString not String so you can write: s.reverse().reverse()).

OTHER TIPS

Not sure if I completely understand the question, but ultimately, if you want your MyString to have all the same methods as String, then at some level your class must also have all of the same methods defined. You can't really get around this.

You can probably come up with neat ways so that for every method you don't have to type return text.blah(), something more elegant than that; but I don't see any way how you could avoid having the method definitions in your MyString at all.

You can't do this as you have to write the methods to expose them for use. But, for example, you can use the Netbeans' "Create Delegates..." feature and you get all delegate methods with some mouse clicks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top