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

后端 未结 15 2132
再見小時候
再見小時候 2020-11-27 06:36

I\'d like to add a method AddDefaultNamespace() to the String class in Java so that I can type \"myString\".AddDefaultNamespace() instead of

相关标签:
15条回答
  • 2020-11-27 06:58

    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.

    0 讨论(0)
  • 2020-11-27 06:59

    All is said by the other contributors before. You can not extend String directly because it is final.

    If you would use Scala, you can use implicit conversions like this:

    object Snippet {
      class MyString(s:String) {
        def addDefaultNamespace = println("AddDefaultNamespace called")
      }
      implicit def wrapIt(s:String) = new MyString(s)
    
      /** test driver */
      def main(args:Array[String]):Unit = {
        "any java.io.String".addDefaultNamespace // !!! THAT is IT! OR?
      }
    
    0 讨论(0)
  • 2020-11-27 07:05

    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.

    public class ObjectMap extends HashMap<String, Object> {
    
        public Map<String, Object> map;
    
        public ObjectMap(Map<String, Object> map){
            this.map = map;
        }
    
        public int getInt(String K) {
            return Integer.valueOf(map.get(K).toString());
        }
    
        public String getString(String K) {
            return String.valueOf(map.get(K));
        }
    
        public boolean getBoolean(String K) {
            return Boolean.valueOf(map.get(K).toString());
        }
    
        @SuppressWarnings("unchecked")
        public List<String> getListOfStrings(String K) {
            return (List<String>) map.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public List<Integer> getListOfIntegers(String K) {
            return (List<Integer>) map.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public List<Map<String, String>> getListOfMapString(String K) {
            return (List<Map<String, String>>) map.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public List<Map<String, Object>> getListOfMapObject(String K) {
            return (List<Map<String, Object>>) map.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public Map<String, Object> getMapOfObjects(String K) {
            return (Map<String, Object>) map.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public Map<String, String> getMapOfStrings(String K) {
            return (Map<String, String>) map.get(K);
        }
    }
    

    Now define a new Instance of this class as:

    ObjectMap objectMap = new ObjectMap(new HashMap<String, Object>();
    

    Now you can access all the method of the built-in Map class, and also the newly implemented methods.

    objectMap.getInt("KEY");
    

    EDIT:

    In the above code, for accessing the built-in methods of map class, you'd have to use

    objectMap.map.get("KEY");
    

    Here's an even better solution:

    public class ObjectMap extends HashMap<String, Object> {
    
        public ObjectMap() {
    
        }
    
        public ObjectMap(Map<String, Object> map){
            this.putAll(map);
        }
    
        public int getInt(String K) {
            return Integer.valueOf(this.get(K).toString());
        }
    
        public String getString(String K) {
            return String.valueOf(this.get(K));
        }
    
        public boolean getBoolean(String K) {
            return Boolean.valueOf(this.get(K).toString());
        }
    
        @SuppressWarnings("unchecked")
        public List<String> getListOfStrings(String K) {
            return (List<String>) this.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public List<Integer> getListOfIntegers(String K) {
            return (List<Integer>) this.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public List<Map<String, String>> getListOfMapString(String K) {
            return (List<Map<String, String>>) this.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public List<Map<String, Object>> getListOfMapObject(String K) {
            return (List<Map<String, Object>>) this.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public Map<String, Object> getMapOfObjects(String K) {
            return (Map<String, Object>) this.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public Map<String, String> getMapOfStrings(String K) {
            return (Map<String, String>) this.get(K);
        }
    
        @SuppressWarnings("unchecked")
        public boolean getBooleanForInt(String K) {
            return Integer.valueOf(this.get(K).toString()) == 1 ? true : false;
        }
    }
    

    Now you don't have to call

    objectMap.map.get("KEY");
    

    simply call

    objectMap.get("KEY");
    
    0 讨论(0)
  • 2020-11-27 07:10

    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 .

    0 讨论(0)
  • 2020-11-27 07:11

    Better use StringBuilder, which has method append() and does the job you want. The String class is final and can not be extended.

    0 讨论(0)
  • 2020-11-27 07:12

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

    0 讨论(0)
提交回复
热议问题