1

I need to add a custom method on java.lang.String class

I am looking for a java equivalent to the C# extension methods feature.

...is there any language feature that will allow me to write an extension method for a final class ?

my code in c#:

public static string GetLang(this string value, bool isSplited = false, LanguageType? languageType = null)
        {
            if (String.IsNullOrWhiteSpace(value))
                return null;

            var language = (languageType ?? LanguageProvider.Language).ToString().ToLower();

            if (isSplited)
            {
                var items = new List<string>();
                foreach (var item in value.Split('|'))
                {
                    var multiLang = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);

                    if (multiLang.TryGetValue(language, out string textValue))
                    {
                        items.Add(textValue);
                    }
                    else
                    {
                        items.Add($"[{language}]");
                    }
                }

                return string.Join(" ", items);
            }
            else
            {
                var multiLang = JsonConvert.DeserializeObject<Dictionary<string, string>>(value);

                if (multiLang.TryGetValue(language, out string textValue))
                {
                    return textValue;
                }
                else
                {
                    return $"[{language}]";
                }

            }
        }

i want use this similar feature in Java

Aslami.dev
  • 880
  • 8
  • 19

3 Answers3

2

You cannot. Java Strings are immutable, and to ensure people do not break immutability doing what you have asked, the class is final. What need do you have of adding a new method on strings?

Immutability of Strings in Java

Martin'sRun
  • 522
  • 3
  • 11
0

Unfortunately, Java does not support extension methods.

shy4blue
  • 46
  • 5
  • [Java equivalent to C# extension methods](https://stackoverflow.com/questions/4359979/java-equivalent-to-c-sharp-extension-methods) – shy4blue Sep 29 '19 at 14:12
0

You cannot extend String class or any other final class but you can always use composition to make use of String class and add your own functionality to it -

   Class CustomString {
      private String str; // composition
      CustomString(String s) {
        str = s;
      }
      public String getStr() {
         return str;
      }
      // .. your custom method 
      public String anyLogicGoesHere() {
      }
}
Akash
  • 4,412
  • 4
  • 30
  • 48