开发者

Dynamically Assign a property on a POJO in Groovy

开发者 https://www.devze.com 2023-01-11 13:28 出处:网络
If I have a Java cla开发者_Go百科ss with the properties \"firstName\" and \"lastName\", I want to dynamically assign the property based on variables. To give an example:

If I have a Java cla开发者_Go百科ss 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


You could also use

instance.setProperty(varname,value)

or maybe

instance[varname] = value


Nevermind, it's

instance.@"$varname" = value
0

精彩评论

暂无评论...
验证码 换一张
取 消