我即将重载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!" } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。