Mike Axiak
Mike Axiak

Reputation: 11996

Dynamically Assign a property on a POJO in Groovy

If I have a Java class with the properties "firstName" and "lastName", I want to dynamically assign the property based on variables. To give an example:

public class MyClass {
    public String firstName;
    public String lastName;
}

...
def varname = "firstName";
def value = "Smith";
def instance = new MyClass();
/* Something like the following */
instance.$varname = value;

I know in python I could use setattr(instance, varname, value). This is kind of the opposite of setProperty.

Thanks

Upvotes: 2

Views: 881

Answers (2)

towe75
towe75

Reputation: 1470

You could also use

instance.setProperty(varname,value)

or maybe

instance[varname] = value

Upvotes: 1

Mike Axiak
Mike Axiak

Reputation: 11996

Nevermind, it's

instance.@"$varname" = value

Upvotes: 0

Related Questions