1

I want to overload the chop method of StringUtils to remove the last character if it is a backslash(\).

Is it possible to overload the function or I need to use an if condition?

Rajat Jain
  • 1,339
  • 2
  • 16
  • 29
  • 2
    Do you mean override? – Anatolii Jun 15 '18 at 13:58
  • 1
    If you wanna override it then it's not possible in the classic sense because it's a static method. – Anatolii Jun 15 '18 at 13:59
  • 2
    `StringUtils` is a class from Apache Commons library right? Overloading means you want to create a method with the same name but different params (basically!). What are you going to do ? Donwload apache commons source code, change the class build jar and use it ? – ikos23 Jun 15 '18 at 14:00
  • Honestly my boss told me to try to do so and that it would be muche more cleaner! But I have no clue how to do it :( – Mohamed-Ali Elakhrass Jun 15 '18 at 14:04

2 Answers2

4

Why not this instead?

StringUtils.removeEnd(s,"\\")
Matthew McPeak
  • 17,705
  • 2
  • 27
  • 59
3

yes, use an if statement. You can't override a static method and it would be too much anyway to create it's own class just for that.

I have an alternative that I personally like:

public static String chopIf(Predicate<String> p, String s) {
    if (p.test(s)) {
        return s.substring(0, s.length()-1); //or StringUtils.chop(s)
    }
    return s;
}

public static void main(String[] args) {
    String test = "qwert\\";
    System.out.println(chopIf(s -> s.endsWith("\\"), test));
}

Something like that. Then you can use it for any character. Tweak it according to need.

Jack Flamp
  • 1,223
  • 1
  • 16
  • 32