0

I want to write a custom method for the String class so that I can call it like the following:

String s = "hello world";
s.myMethod();

Is their a way to accomplish specifically this?

If not then I will just do the following, but I would still like to know.

myMethod(s);

2 Answers2

3

This cannot be done because you can't add methods to existing classes in Java.

It's even more interesting because the class String in Java is a final class, which cannot be subclassed.

You may be interested in this Stack Overflow answer because the thing you are describing is known as monkeypatching, which is common in more dynamic languages than Java. One of the answers links to cglib, one of several libraries that do some magic with the bytecode. Try hard enough and violate basic principles and you can do quite a bit, including making 5 be 3.

Update: This question and its answers seem to address your exact question. Some of the answers are pretty creative.

halfer
  • 19,824
  • 17
  • 99
  • 186
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • Thanks for the info. One quick clarification question: from your link it sounds like monkey patching involves replacing a class's already existing method. Is adding brand new methods (without replacing old ones) also referred to as monkey patching? – the0dark0one Jan 23 '16 at 23:41
  • It's true that it is hard to precisely determine an exact meaning for "monkeypatching" but as is the case with all words, its meaning may evolve a bit over time. Some might restrict the term to mean only replacing methods in a dynamic programming languages, while others might include any kind of runtime modification to a class whatsoever. In the wider context of the term (the one I happen to like), yes, monkeypatching does include adding methods to a class. This is different from subclassing though, which is the way to "add methods" to a Java class. – Ray Toal Jan 25 '16 at 01:25
1

It is not possible. The best aproach in java would be create your own class that extends from string and write there your method. This way your class would be like string class but including your stuff.

but is not possible because string is final. So create a class that contains just a string object and write ther your method refering to the string. So you can invoke string methods through your string object in your class, and invoke your method through your class directly

Oldskultxo
  • 945
  • 8
  • 19