[英]Java how can i create my own methods which are calling via dot operator
For example we have.toString() but we don't have.toStringAndTrim() or.toStringAndReplace().例如我们有.toString() 但我们没有.toStringAndTrim() 或.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?如何在 java 中做到这一点? Is this possible?这可能吗?
Java how can i create my own methods which are calling via dot operator Java 我如何创建自己的通过点运算符调用的方法
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; Java 没有提供这样的机制; other languages such as Kotlin do.其他语言,例如Kotlin可以。
All you can do is to define a method which takes the "receiver" as the first parameter, eg您所能做的就是定义一个将“接收者”作为第一个参数的方法,例如
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.您可能希望能够将其写为thing.toStringAndTrim()
,但这在 Java 中是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.