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

后端 未结 15 2134
再見小時候
再見小時候 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 07:19

    The class declaration says it all pretty much,as you cannot inherit it becouse it's final. You can ofcourse implement your own string-class, but that is probaby just a hassle.

    public final class String
    

    C# (.net 3.5) have the functionality to use extender metods but sadly java does not. There is some java extension called nice http://nice.sourceforge.net/ though that seems to add the same functionality to java.

    Here is how you would write your example in the Nice language (an extension of Java):

    private String someMethod(String s)
    {
       return s.substring(0,1);
    
    }
    
    void main(String[] args)
    {
       String s1 = "hello";
       String s2 = s1.someMethod();
       System.out.println(s2);
    
    }
    

    You can find more about Nice at http://nice.sf.net

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

    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.

    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.

    Had String been mutable or not final, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"

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

    As everybody else has said, no you can't subclass String because it's final. But might something like the following help?

    public final class NamespaceUtil {
    
        // private constructor cos this class only has a static method.
        private NamespaceUtil() {}
    
        public static String getDefaultNamespacedString(
                final String afterDotString) {
            return DEFAULT_NAMESPACE + "." + afterDotString;
        }
    
    }
    

    or maybe:

    public final class NamespacedStringFactory {
    
        private final String namespace;
    
        public NamespacedStringFactory(final String namespace) {
            this.namespace = namespace;
        }
    
        public String getNamespacedString(final String afterDotString) {
            return namespace + "." + afterDotString;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题