shabinjo
shabinjo

Reputation: 1561

How to find the key of a map is exist in an Object as a property in groovy?

Map map=[firstName:test,lastName:user]

There is a pojo

 public class User{

   private String firstName;
   private String lastName;

     public String getFirstName() {
       return firstName;
     }

     public void setFirstName(String firstName) {
      this.firstName = firstName;
     }

     public String getLastName() {
        return lastName;
      }

     public void setLastName(String lastName) {
         this.lastName = lastName;
      }
    }

Is there a way to find out these keys in map are exist in User object as a property? if yes, assign the value of that key to the corresponding object property.without hard coding the key or value.

Upvotes: 0

Views: 1720

Answers (3)

shabinjo
shabinjo

Reputation: 1561

As @Lino suggested on above comment,I tried below and it seems working fine.Anybody has any comment on performance of this implementation,since it is through reflection?

  map?.each {field ->
          String objProp=User.getClass().declaredFields.find{it?.name?.equalsIgnoreCase(field?.key)}?.getName()
          if(objProp!=null) User."${objProp}"= field.value
      }

Upvotes: 0

Rao
Rao

Reputation: 21359

You may achieve it in below ways.

Map as Object of the Class

Map map = [firstName:'test',lastName:'user']
//If the properties does not match exactly, you get exception with this
def user = map as User
println user.firstName
println user.lastName

Check and Assign the property

def user2 = new User()
map.keySet().each { if (user2.hasProperty(it)) {user2."${it}" = map[it]} }
println user2.firstName
println user2.lastName

Upvotes: 1

tim_yates
tim_yates

Reputation: 171054

If you have an instance of User, you can use hasProperty, ie:

assert aUser.hasProperty('firstName')

Upvotes: 0

Related Questions