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

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

<p>Thanks and regards.</p>

[{'answer_id': 81803, 'author': 'GustyWind', 'author_id': 11114, 'author_profile': 'https://Stackoverflow.com/users/11114', 'pm_score': 7, 'selected': True, 'text': '<p><code>String</code> is a final class which means it cannot be extended to work on your own implementation.</p>\n'}, {'answer_id': 81817, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 3, 'selected': False, 'text': "<p>It is not possible, since String is a final class in Java. </p>\n\n<p>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.</p>\n"}, {'answer_id': 81835, 'author': 'Sietse', 'author_id': 6400, 'author_profile': 'https://Stackoverflow.com/users/6400', 'pm_score': 2, 'selected': False, 'text': "<p>Not possible, and that's a good thing. A String is a String. It's behaviour is defined, deviating from it would be evil. Also, it's marked final, meaning you couldn't subclass it even if you wanted to.</p>\n"}, {'answer_id': 81837, 'author': 'm_pGladiator', 'author_id': 446104, 'author_profile': 'https://Stackoverflow.com/users/446104', 'pm_score': 1, 'selected': False, 'text': '<p>Better use StringBuilder, which has method append() and does the job you want. The String class is final and can not be extended.</p>\n'}, {'answer_id': 81871, 'author': 'Carl-Johan', 'author_id': 15406, 'author_profile': 'https://Stackoverflow.com/users/15406', 'pm_score': 2, 'selected': False, 'text': '<p>The class declaration says it all pretty much,as you cannot inherit it becouse it\'s final.\nYou can ofcourse implement your own string-class, but that is probaby just a hassle.</p>\n\n<pre><code>public final class String\n</code></pre>\n\n<p>C# (.net 3.5) have the functionality to use extender metods but sadly java does not. There is some java extension called nice <a href="http://nice.sourceforge.net/" rel="nofollow noreferrer">http://nice.sourceforge.net/</a> though that seems to add the same functionality to java.</p>\n\n<p>Here is how you would write your example in the Nice language (an extension of\nJava):</p>\n\n<pre><code>private String someMethod(String s)\n{\n   return s.substring(0,1);\n\n}\n\nvoid main(String[] args)\n{\n   String s1 = "hello";\n   String s2 = s1.someMethod();\n   System.out.println(s2);\n\n}\n</code></pre>\n\n<p>You can find more about Nice at <a href="http://nice.sf.net" rel="nofollow noreferrer">http://nice.sf.net</a> </p>\n'}, {'answer_id': 81889, 'author': 'Martin Spamer', 'author_id': 15527, 'author_profile': 'https://Stackoverflow.com/users/15527', 'pm_score': 0, 'selected': False, 'text': '<p>The Java String class is a final, making it immutable.  This is for efficiency reasons and that it would be extremely difficult to logically extend without error; the implementers have therefore chosen to make it a final class meaning it cannot be extended with inheritance.</p>\n\n<p>The functionality you wish your class to support is not properly part of the regular responsibilities of a String as per the <a href="http://www.oodesign.com/single-responsibility-principle.html" rel="nofollow noreferrer">single responsibility principle</a>, a namespace it is a different abstraction, it is more specialised.  You should therefore define a new class, which includes String a member and supports the methods you need to provide the namespace management you require.</p>\n\n<p>Do not be afraid to add abstractions (classes) these are the essence of good OO design.</p>\n\n<p>Try using a <a href="http://en.wikipedia.org/wiki/Class-Responsibility-Collaboration_card" rel="nofollow noreferrer">class responsibility collaboration (CRC) card</a>  to clarify the abstraction you need.  </p>\n'}, {'answer_id': 81891, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>You can create your own version of String class and add a method :-)</p>\n'}, {'answer_id': 81917, 'author': 'Vhaerun', 'author_id': 11234, 'author_profile': 'https://Stackoverflow.com/users/11234', 'pm_score': -1, 'selected': False, 'text': '<p>Actually , you can modify the String class . If you edit the String.java file located in src.zip , and then rebuild the rt.jar , the String class will have more methods added by you . The downside is that that code will only work on your computer , or if you provide your String.class , and place it in the classpath before the default one .</p>\n'}, {'answer_id': 81946, 'author': 'MB.', 'author_id': 11961, 'author_profile': 'https://Stackoverflow.com/users/11961', 'pm_score': 2, 'selected': False, 'text': '<p>As everybody else has said, no you can\'t subclass String because it\'s final.  But might something like the following help?</p>\n\n<pre><code>public final class NamespaceUtil {\n\n    // private constructor cos this class only has a static method.\n    private NamespaceUtil() {}\n\n    public static String getDefaultNamespacedString(\n            final String afterDotString) {\n        return DEFAULT_NAMESPACE + "." + afterDotString;\n    }\n\n}\n</code></pre>\n\n<p>or maybe:</p>\n\n<pre><code>public final class NamespacedStringFactory {\n\n    private final String namespace;\n\n    public NamespacedStringFactory(final String namespace) {\n        this.namespace = namespace;\n    }\n\n    public String getNamespacedString(final String afterDotString) {\n        return namespace + "." + afterDotString;\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 83552, 'author': 'Alex Miller', 'author_id': 7671, 'author_profile': 'https://Stackoverflow.com/users/7671', 'pm_score': 4, 'selected': False, 'text': "<p>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.</p>\n\n<p>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.  </p>\n"}, {'answer_id': 2077551, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>All is said by the other contributors before. You can not extend String directly because it is final.</p>\n\n<p>If you would use Scala, you can use implicit conversions like this:</p>\n\n<pre><code>object Snippet {\n  class MyString(s:String) {\n    def addDefaultNamespace = println("AddDefaultNamespace called")\n  }\n  implicit def wrapIt(s:String) = new MyString(s)\n\n  /** test driver */\n  def main(args:Array[String]):Unit = {\n    "any java.io.String".addDefaultNamespace // !!! THAT is IT! OR?\n  }\n</code></pre>\n'}, {'answer_id': 6806424, 'author': 'Aldo Barreras', 'author_id': 860157, 'author_profile': 'https://Stackoverflow.com/users/860157', 'pm_score': 5, 'selected': False, 'text': '<p>Well, actually everyone is being unimaginative. I needed to write my own version of startsWith method because I needed one that was case insensitive.</p>\n\n<pre><code>class MyString{\n    public String str;\n    public MyString(String str){\n        this.str = str;\n    }\n    // Your methods.\n}\n</code></pre>\n\n<p>Then it\'s quite simple, you make your String as such:</p>\n\n<pre><code>MyString StringOne = new MyString("Stringy stuff");\n</code></pre>\n\n<p>and when you need to call a method in the String library, simple do so like this:</p>\n\n<pre><code>StringOne.str.equals("");\n</code></pre>\n\n<p>or something similar, and there you have it...extending of the String class.</p>\n'}, {'answer_id': 37406295, 'author': 'Drunken Daddy', 'author_id': 2067264, 'author_profile': 'https://Stackoverflow.com/users/2067264', 'pm_score': 2, 'selected': False, 'text': '<p>People searching with keywords "add method to built in class" might end up here. If you\'re looking to add method to a non final class such as HashMap, you can do something like this. </p>\n\n<pre><code>public class ObjectMap extends HashMap&lt;String, Object&gt; {\n\n    public Map&lt;String, Object&gt; map;\n\n    public ObjectMap(Map&lt;String, Object&gt; map){\n        this.map = map;\n    }\n\n    public int getInt(String K) {\n        return Integer.valueOf(map.get(K).toString());\n    }\n\n    public String getString(String K) {\n        return String.valueOf(map.get(K));\n    }\n\n    public boolean getBoolean(String K) {\n        return Boolean.valueOf(map.get(K).toString());\n    }\n\n    @SuppressWarnings("unchecked")\n    public List&lt;String&gt; getListOfStrings(String K) {\n        return (List&lt;String&gt;) map.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public List&lt;Integer&gt; getListOfIntegers(String K) {\n        return (List&lt;Integer&gt;) map.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public List&lt;Map&lt;String, String&gt;&gt; getListOfMapString(String K) {\n        return (List&lt;Map&lt;String, String&gt;&gt;) map.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public List&lt;Map&lt;String, Object&gt;&gt; getListOfMapObject(String K) {\n        return (List&lt;Map&lt;String, Object&gt;&gt;) map.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public Map&lt;String, Object&gt; getMapOfObjects(String K) {\n        return (Map&lt;String, Object&gt;) map.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public Map&lt;String, String&gt; getMapOfStrings(String K) {\n        return (Map&lt;String, String&gt;) map.get(K);\n    }\n}\n</code></pre>\n\n<p>Now define a new Instance of this class as:</p>\n\n<pre><code>ObjectMap objectMap = new ObjectMap(new HashMap&lt;String, Object&gt;();\n</code></pre>\n\n<p>Now you can access all the method of the built-in Map class, and also the newly implemented methods.</p>\n\n<pre><code>objectMap.getInt("KEY");\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>In the above code, for accessing the built-in methods of map class, you\'d have to use </p>\n\n<pre><code>objectMap.map.get("KEY");\n</code></pre>\n\n<p>Here\'s an even better solution:</p>\n\n<pre><code>public class ObjectMap extends HashMap&lt;String, Object&gt; {\n\n    public ObjectMap() {\n\n    }\n\n    public ObjectMap(Map&lt;String, Object&gt; map){\n        this.putAll(map);\n    }\n\n    public int getInt(String K) {\n        return Integer.valueOf(this.get(K).toString());\n    }\n\n    public String getString(String K) {\n        return String.valueOf(this.get(K));\n    }\n\n    public boolean getBoolean(String K) {\n        return Boolean.valueOf(this.get(K).toString());\n    }\n\n    @SuppressWarnings("unchecked")\n    public List&lt;String&gt; getListOfStrings(String K) {\n        return (List&lt;String&gt;) this.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public List&lt;Integer&gt; getListOfIntegers(String K) {\n        return (List&lt;Integer&gt;) this.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public List&lt;Map&lt;String, String&gt;&gt; getListOfMapString(String K) {\n        return (List&lt;Map&lt;String, String&gt;&gt;) this.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public List&lt;Map&lt;String, Object&gt;&gt; getListOfMapObject(String K) {\n        return (List&lt;Map&lt;String, Object&gt;&gt;) this.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public Map&lt;String, Object&gt; getMapOfObjects(String K) {\n        return (Map&lt;String, Object&gt;) this.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public Map&lt;String, String&gt; getMapOfStrings(String K) {\n        return (Map&lt;String, String&gt;) this.get(K);\n    }\n\n    @SuppressWarnings("unchecked")\n    public boolean getBooleanForInt(String K) {\n        return Integer.valueOf(this.get(K).toString()) == 1 ? true : false;\n    }\n}\n</code></pre>\n\n<p>Now you don\'t have to call</p>\n\n<pre><code>objectMap.map.get("KEY");\n</code></pre>\n\n<p>simply call</p>\n\n<pre><code>objectMap.get("KEY");\n</code></pre>\n'}, {'answer_id': 45282404, 'author': 'Vpn_talent', 'author_id': 6011941, 'author_profile': 'https://Stackoverflow.com/users/6011941', 'pm_score': 1, 'selected': False, 'text': '<p>No You Cannot Modify String Class in java. Because It\'s final class. and every method present in final class by default will be final.</p>\n\n<p>The absolutely most important reason that String is immutable or final is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.</p>\n\n<p>Had String been mutable or not final, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"</p>\n'}, {'answer_id': 50412907, 'author': 'PaulB', 'author_id': 5335776, 'author_profile': 'https://Stackoverflow.com/users/5335776', 'pm_score': 2, 'selected': False, 'text': '<p><strong>YES!</strong></p>\n\n<p>Based on your requirements (add a different namespace to a String and not use a derived class) you could use project Lombok to do just that and use functionality on a String like so:</p>\n\n<pre><code>String i = "This is my String";\ni.numberOfCapitalCharacters(); // = 2\n</code></pre>\n\n<p>Using Gradle and IntelliJ idea follow the steps below:</p>\n\n<ol>\n<li>Download the lombok plugin from intelliJ plugins repository.</li>\n<li>add lombok to dependencies in gradle like so: <code>compileOnly \'org.projectlombok:lombok:1.16.20\'</code></li>\n<li>go to <code>"Settings &gt; Build &gt; Compiler &gt; Annotation Processors"</code> and enable annotation processing</li>\n<li><p>create a class with your extension functions and add a static method like this: </p>\n\n<pre><code>public class Extension {\n    public static String appendSize(String i){\n        return i + " " + i.length();\n    }\n}\n</code></pre></li>\n<li><p>annotate the class where you want to use your method like this:</p>\n\n<pre><code>import lombok.experimental.ExtensionMethod;\n\n@ExtensionMethod({Extension.class})\npublic class Main {\n    public static void main(String[] args) {\n        String i = "This is a String!";\n        System.out.println(i.appendSize());\n    }\n}\n</code></pre></li>\n</ol>\n\n<p>Now you can use the method <code>.appendSize()</code> on any string in any class as long as you have annotated it and the produced result for the above example</p>\n\n<blockquote>\n  <p>This is a String!</p>\n</blockquote>\n\n<p>would be: </p>\n\n<blockquote>\n  <p>This is a String! 17</p>\n</blockquote>\n'}, {'answer_id': 74656039, 'author': 'Ogün', 'author_id': 10480017, 'author_profile': 'https://Stackoverflow.com/users/10480017', 'pm_score': 0, 'selected': False, 'text': '<p>You can do this easily with Kotlin. You can run both the kotlin code from within the java and the java code from the kotlin.</p>\n<p>Difficult jobs that you can do with Java can be done more easily with Kotlin. I recommend every java developer to learn kotlin.</p>\n<p>Referance: <a href="https://kotlinlang.org/docs/java-to-kotlin-interop.html" rel="nofollow noreferrer">https://kotlinlang.org/docs/java-to-kotlin-interop.html</a></p>\n<p>Example:</p>\n<p>Kotlin StringUtil.kt File</p>\n<pre><code>@file:JvmName(&quot;StringUtil&quot;)\npackage com.example\n\nfun main() {\nval x: String = &quot;xxx&quot;\nprintln(x.customMethod())\n}\n\nfun String.customMethod(): String = this + &quot; ZZZZ&quot;\n</code></pre>\n<p>Java Code:</p>\n<pre><code>package com.example;\n\npublic class AppStringCustomMethod {\n\npublic static void main(String[] args) {\n    String kotlinResponse = StringUtil.customMethod(&quot;ffff&quot;);\n    System.out.println(kotlinResponse);\n}\n}\n</code></pre>\n<p>output:</p>\n<p>ffff ZZZZ</p>\n'}]
['https://Stackoverflow.com/questions/81786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15546/']