Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify if an object has certain property?

Tags:

groovy

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    } } 
like image 576
Roman Avatar asked Oct 17 '12 15:10

Roman


2 Answers

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") {     ... } 
like image 75
ataylor Avatar answered Sep 22 '22 13:09

ataylor


Assuming your object is a Groovy class, you can use hasProperty in the object metaClass like so:

def printName( o ) {   if( o.metaClass.hasProperty( o, 'name' ) && o.name ) {     println "Printing Name : $o.name"   }   else {     println o   } } 

So, then given two classes:

class Named {   String name   int age    String toString() { "toString Named:$name/$age" } }  class Unnamed {   int age    String toString() { "toString Unnamed:$age" } } 

You can create instance of them, and test:

def a = new Named( name: 'tim', age: 21 ) def b = new Unnamed( age: 32 )  printName( a ) printName( b ) 

Which should output:

Printing Name : tim toString Unnamed:32 
like image 34
tim_yates Avatar answered Sep 20 '22 13:09

tim_yates