Groovy:如果object是String,则在运行时检查

use*_*351 5 groovy

我即将重载leftShift运算符,并想知道如何检查给定参数"other"是否为String?

def leftShift(other){
    if(other.getClass() instanceof String){
        println other.toString() + " is a string!"          
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用..任何人都可以帮助我吗?

Jas*_*nM1 10

您可以使用通常在Java中使用的测试.

def leftShift(other) {
    if(other instanceof String) {
        println "$other is a string!"
    }
}
Run Code Online (Sandbox Code Playgroud)

当你调用other.getClass()结果类时,java.lang.Class实例可以与String.class进行比较.注意其他可以为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
Run Code Online (Sandbox Code Playgroud)

输出:

It is currently Thu Aug 21 15:42:55 EDT 2014
org.codehaus.groovy.runtime.GStringImpl
false
true
Run Code Online (Sandbox Code Playgroud)

GStringImpl扩展了GString,它具有使其表现为String对象的方法,并像String类一样实现CharSequence接口.检查其他对象是否为CharSequence,如果object是String或GString实例,则为true.

def leftShift(other) {
    if(other instanceof CharSequence) {
        println "$other is a string!"
    }
}
Run Code Online (Sandbox Code Playgroud)


use*_*772 6

它是

if (other.getClass() == String)
Run Code Online (Sandbox Code Playgroud)