我即将重载左移运算符,并希望知道如何检查给定的参数“other”是否为字符串?
def leftShift(other){
if(other.getClass() instanceof String){
println other.toString() + " is a string!"
}
但是这并不起作用... 有人能帮我吗?
我即将重载左移运算符,并希望知道如何检查给定的参数“other”是否为字符串?
def leftShift(other){
if(other.getClass() instanceof String){
println other.toString() + " is a string!"
}
您可以使用通常在Java中使用的测试。
def leftShift(other) {
if(other instanceof String) {
println "$other is a string!"
}
}
当您调用other.getClass()
时,结果类是java.lang.Class实例,您可以将其与String.class进行比较。注意,other可能为null,在这种情况下,“other instanceof String”的测试结果为false。def x = "It is currently ${ new Date() }"
println x.getClass().getName()
println x instanceof String
println x instanceof CharSequence
输出:
It is currently Thu Aug 21 15:42:55 EDT 2014
org.codehaus.groovy.runtime.GStringImpl
false
true
GStringImpl扩展了GString,它具有使其表现为字符串对象的方法,并像String类一样实现CharSequence接口。如果other对象是CharSequence,则检查是否为String或GString实例。
def leftShift(other) {
if(other instanceof CharSequence) {
println "$other is a string!"
}
}
It is
if (other.getClass() == String)
代码编写有误 - 你缺少一个大括号。如果有了它,instanceof
就像在 Java 中一样工作,正如其他人所提到的那样。然而,在 Groovy 中,我会小心地检查 instanceof
是否针对 String
进行检查,因为有时看起来像是 Strings
的东西实际上是 GStrings
(请参见docs,第 "GStrings aren't Strings" 部分)。快速示例:
assert "the quick brown $somevar jumped over the lazy dog" instanceof String == false
String
和GString
,最好测试CharSequence
:if (other instanceof CharSequence) { ...}
- qlown