Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a method to String class in Java/Android like with category in objective C on iPhone

I need to add a method to the String class in an Android app so I can call it like

String myStr;
x = myStr.myNewMethod(3);

I don't have any idea how I could do this in Java.

ps I do not want to create a Subclass of String. This would mean that I need to do coercion all over and/or declare my Strings as a new Class.

Many thanks

like image 601
user387184 Avatar asked Jun 22 '26 06:06

user387184


2 Answers

String is a final class in Java, which means you cannot subclass it. This is an important trait of the class, because as Strings are used all over the place, especially for security tokens and the like. Being able to modify its behavior after the fact would potentially cause security issues.

Unfortunately there is no way to add categories in Java. The only thing you could do (and have done) if you need some custom functionality often, is to create a utilities class, maybe with some static methods that you could then import statically into your application code.

This is, however, just a crude workaround, but probably the best you can get.

like image 82
Daniel Schneller Avatar answered Jun 24 '26 20:06

Daniel Schneller


Without creating either a subclass (inhertance) or a wrapper class (composition) you cannot do this.

Just write a static helper method that takes a string and whatever other parameters you need.

static Foo myNewMethod(String s, int x)
{
    // snip...
    return someFoo;
}

// later...
String myStr = "foo";
Foo f = myNewMethod(myStr, 3);
like image 33
Matt Ball Avatar answered Jun 24 '26 18:06

Matt Ball