Extend java.lang.String

前端 未结 5 920
甜味超标
甜味超标 2020-12-15 16:43

java.lang.String is declared as final, however are there any mechanisms available legitimate or otherwise to extend it and replace the equals(String other) method?

相关标签:
5条回答
  • 2020-12-15 17:07

    Now, there is a way. With manifold it's possible to extend every Java Class. Here is an example for String:

    package extensions.java.lang.String;
    
    import manifold.ext.api.*;
    
    @Extension
    public class MyStringExtension {
    
      public static void print(@This String thiz) {
        System.out.println(thiz);
      }
    
      @Extension
      public static String lineSeparator() {
        return System.lineSeparator();
      }
    }
    

    Can than be used as follow:

    String name = "Manifold";
    name.print();
    String.lineSeparator();
    

    Another example can be found here: https://jaxenter.com/manifold-code-generator-part-2-151762.html

    Notice, that manifold is still alpha.

    0 讨论(0)
  • 2020-12-15 17:11

    It is not possible to directly inherit String class as it is final. Also wrapper classes java.lang.Integer, java.lang.Float, etc... are final.

    0 讨论(0)
  • 2020-12-15 17:15

    No, absolutely not. If you want some "other" kind of string, create another type which might contain a string:

    public final class OtherString {
        private final String underlyingString;
    
        public OtherString(String underlyingString) {
            this.underlyingString = underlyingString;
        }        
    
        // Override equals however you want here
    }
    
    0 讨论(0)
  • 2020-12-15 17:15

    You cannot extend a class that is marked as final. You can use composition to either put a String object inside or you can hand roll your own version. This can be accomplished via character arrays and the other magic that goes into creating String classes.

    0 讨论(0)
  • 2020-12-15 17:17

    I guess the closest you can come is making some class that implements CharSequence. Most JDK string manipulation methods accept a CharSequence. StringBuilder for example. Combined with a good implementation of toString(), the various methods of String and valueOf(), you can come pretty close to a natural substitute.

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