Why does Groovy replace java.lang.String.length() with size()?
Wikipedia当前有关Groovy编程语言的文章解释说:"大多数有效的Java文件也是有效的Groovy文件",并给出了以下示例,首先是Java代码:
1 2 3 |
然后在Groovy中相同:
1 | ["Rod","Carlos","Chris"].findAll{it.size() <= 4}.each{println it} |
在第一个示例中,请注意,我们使用了完全普通的Java方法java.lang.String.length()。在第二个示例中,此方法已神秘地替换为对名为
1 2 3 |
也不会以某种方式向
1 2 3 4 5 | // [...] for (def method : c.getMethods()) { println method.getName() } // prints a whole bunch of method names, no"size" |
,但此代码仍然可以以某种方式起作用:
1 2 | // [...] println s.size() //"0" |
我找不到任何Groovy文档来对此进行解释。
-
size() 来自哪里? - 为什么它不出现在对象上?
- 为什么要添加?
-
length() 有什么问题,为什么不优先使用它? -
java.lang.String 中还添加了哪些其他方法? - 那么其他标准类呢?
Groovy向字符串和各种其他类添加了许多方法。所有便利方法都是Groovy出色的原因之一。
要查看Groovy添加的某些方法,请检查GDK,尤其是CharSequence和Collection。
我建议您阅读Groovy类
Static methods are used with the first parameter being the destination class, e.g.. public static String reverse(String self) provides a reverse() method for String.