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

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

问题描述

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



让我们看一下这个例子:

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


解决方案

您可以使用 hasProperty 。例子:

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

如果你使用一个变量作为属性名称,你可以使用这个:

  String propName ='name'$ b $如果(object.hasProperty(propName)&&&&&& amp;& amp;& amp;& amp;& amp;& amp;& amp;& amp;& > 

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

Let's look at the example:

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
   }
}

解决方案

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天全站免登陆