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

后端 未结 15 2329
再見小時候
再見小時候 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

提交回复
热议问题