Q:

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.

A:

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

