加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 16:27:05 所属栏目:大数据 来源:网络整理
导读:我即将重载leftShift运算符,并想知道如何检查给定参数“other”是否为String? def leftShift(other){ if(other.getClass() instanceof String){ println other.toString() + " is a string!" } 但这不起作用..任何人都可以帮助我吗? 解决方法 您可以使用通
我即将重载leftShift运算符,并想知道如何检查给定参数“other”是否为String?

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进行比较.注意其他可以为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接口.检查其他对象是否为CharSequence,如果object是String或GString实例,则为true.

def leftShift(other) {
    if(other instanceof CharSequence) {
        println "$other is a string!"
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读