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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With