如何验证对象是否具有特定属性? [英] How to verify if an object has certain property?

查看:14
本文介绍了如何验证对象是否具有特定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用预期属性的值或指定的默认值.如何在 groovy 中实现这一点?

I want to use either a value of expected property or a specified default. How to achieve this in groovy?

让我们看一下例子:

def printName(object) {
   //if object has initialized property 'name' - print 'name', otherwise print ToString
   if (object<some code here>name && object.name) {
      print object.name
   } else {
      print object
   }
}

推荐答案

您可以使用 hasProperty.示例:

You can use hasProperty. Example:

if (object.hasProperty('name') && object.name) {
    println object.name
} else {
    println object
}

如果您为属性名称使用变量,则可以使用:

If you're using a variable for the property name, you can use this:

String propName = 'name'
if (object.hasProperty(propName) && object."$propName") {
    ...
}

这篇关于如何验证对象是否具有特定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆