-1

For example we have .toString() but we don't have .toStringAndTrim() or .toStringAndReplace(). So I want to create my own methods inside a library and when I import this library I want to access after dot operator. How can I do this in java? Is this possible?

gurkan
  • 509
  • 1
  • 4
  • 18
  • Every time you write a Java program, you're writing methods. – Dawood ibn Kareem Nov 26 '21 at 08:32
  • But the thing is calling your own methods after any object type like ".ToString()" "getClass()" – gurkan Nov 26 '21 at 08:35
  • no, you can't call it on "any object type", you can't call it on a String, since you can't change the String implementation, you can, however, pass a String as parameter – Stultuske Nov 26 '21 at 08:36
  • For your specific examples, just chain the method calls with calls to other existing methods on the `String` class: `.toString().trim()` and `.toString().replace(...)`. – Andy Turner Nov 26 '21 at 08:38
  • You seem to be asking if Java has something like [Kotlin's Extensions](https://kotlinlang.org/docs/extensions.html): no, it doesn't. – Andy Turner Nov 26 '21 at 08:39
  • I know, these are only example. It can be .skip(2) ,last(5) .convertList() or etc. – gurkan Nov 26 '21 at 08:39
  • @gurkan yet the explanation remains the same. .last(5) can only be called on .skip(2) if the skip(int a) method returns a datatype that provides a last(int a) method – Stultuske Nov 26 '21 at 08:41

1 Answers1

2

Java how can i create my own methods which are calling via dot operator

You can't add methods to existing classes, except for those for which you can change the source. Java doesn't provide such a mechanism; other languages such as Kotlin do.

All you can do is to define a method which takes the "receiver" as the first parameter, e.g.

static String toStringAndTrim(Object receiver) {
  return receiver.toString().trim();
}

and then invoke it like:

toStringAndTrim(thing)

You may want to be able to write this as thing.toStringAndTrim(), but it's just not possible in Java.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243