groovyreflectionproperties

Appropriate way to access a property from its name as a string


I want to access (get or set) the property of an object from the string name of the property. I've found one way to do it:

PropertyValue property = obj.metaPropertyValues.find { it.name == 'propertyName' }

Then, I can use property.value to get or set the value. However, the fact that metaPropertyValues is a List and not a Map makes me feel like there might be a better way. Am I just being paranoid, or is there a better way?


Solution

  • You can use Groovy's dynamic property access with obj["propertyName"] Groovy allows you to access and set properties of objects dynamically

    def value = obj["propertyName"]  // get value
    obj["propertyName"] = newValue   // set value