我即将重载左 Shift 运算符,想知道如何检查给定参数“other”是否为 Strong?
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。
更新:
这是一个创建 Groovy 的简单案例 GString不是字符串实例的实例:
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 对象的方法,并像 String 类一样实现 CharSequence 接口(interface)。检查其他对象是否为 CharSequence,如果对象是 String 或 GString 实例,则为 true。
def leftShift(other) {
if(other instanceof CharSequence) {
println "$other is a string!"
}
}




