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

后端 未结 15 2237
再見小時候
再見小時候 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: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;
        }
    
    }
    

提交回复
热议问题