Can I add new methods to the String class in Java?

I'd like to add a method AddDefaultNamespace() to the String class in Java so that I can type "myString".AddDefaultNamespace() instead of DEFAULTNAMESPACE + "myString", to obtain something like "MyDefaultNameSpace.myString". I don't want to add another derived class either (PrefixedString for example).

Maybe the approach is not good for you but I personally hate using +. But, anyway, is it possible to add new methods to the String class in Java?

Thanks and regards.


Solution 1:

String is a final class which means it cannot be extended to work on your own implementation.

Solution 2:

Well, actually everyone is being unimaginative. I needed to write my own version of startsWith method because I needed one that was case insensitive.

class MyString{
    public String str;
    public MyString(String str){
        this.str = str;
    }
    // Your methods.
}

Then it's quite simple, you make your String as such:

MyString StringOne = new MyString("Stringy stuff");

and when you need to call a method in the String library, simple do so like this:

StringOne.str.equals("");

or something similar, and there you have it...extending of the String class.

Solution 3:

As everyone else has noted, you are not allowed to extend String (due to final). However, if you are feeling really wild, you can modify String itself, place it in a jar, and prepend the bootclasspath with -Xbootclasspath/p:myString.jar to actually replace the built-in String class.

For reasons I won't go into, I've actually done this before. You might be interested to know that even though you can replace the class, the intrinsic importance of String in every facet of Java means that it is use throughout the startup of the JVM and some changes will simply break the JVM. Adding new methods or constructors seems to be no problem. Adding new fields is very dicey - in particular adding Objects or arrays seems to break things although adding primitive fields seems to work.

Solution 4:

It is not possible, since String is a final class in Java.

You could use a helper method all the time you want to prefix something. If you don't like that you could look into Groovy or Scala, JRuby or JPython both are languages for the JVM compatible with Java and which allow such extensions.