title: Decorating a String in Java
body: <p>Suppose I want to use the Decorator pattern to add functionality to the java.lang.String class.  (Just for example, to add a toRussian() method.)  String is a final class.  Is the following the only way to do it?</p>
  
  <pre><code>class DecoratedString implements Serializable, CharSequence, 
      Comparable&lt;DecoratedString&gt; 
  {
    private final String str;
    public DecoratedString (String str) {
      this.str = str;
    }
    public DecoratedString toRussian() {
       ...
    }
    public String toString() { return str; }
    public int hashCode() { return str.hashCode(); }
    public boolean equals(Object obj) { /* don't forget this one */ } 
    public char charAt(int index) { return str.charAt(index);}
    public int codePointAt(int index) { return str.codePointAt(index);}
    ... and so on for 30 or so more methods of String ...
  }
  </code></pre>
  
  <p>Usage:</p>
  
  <pre><code>String greeting = new DecoratedString("Hello, world!").toRussian().toString();
  </code></pre>
  
  <p>Postscript:  This is so EASY to do in Objective-C with "Categories".  Python now has @Decorators.  And of course it's trivial in JavaScript, where you routinely add trim() to the String prototype.  Is it totally impossible in Java?</p>
  
  <p>Postpostscript:  OK, toRussian() is a bad example.  How would you add trim(), if String didn't already have trim()?  trim() is an example of something every String should have.</p>