Keeely
Keeely

Reputation: 1015

How do I set an attribute on an object in Groovy

I would like to write the equivalent of this Python code in Groovy:

>>> class A(object): pass 
>>> a = A()
>>> name = os.name
>>> setattr(a, name, "some text")
>>> a
<__main__.A object at 0x10aad6a10>
>>> a.posix
'value'

I tried this:

class TmpClass {}
def tmp = new TmpClass()
String name = getNameFromSomeWhere()
tmp.metaClass.setAttribute(tmp, name, "value")

But it throws an exception saying the attribute is not found.

Edit: I've updated the code to reflect the fact that the property/attribute name is not a literal.

Upvotes: 0

Views: 5928

Answers (3)

ernest_k
ernest_k

Reputation: 45339

If you're just looking for a way to set dynamic properties, then the square bracket notation should be enough:

tmp['name'] = 'value'
tmp[propertyName] = propertyValue //runtime property name and value

But if you also need to dynamically grow the object with new fields, etc., and don't want to use a simple map, then you should probably use an Expando (instead of a class), which supports adding dynamic properties and closures:

def tmp = new Expando()
tmp['name'] = 'value'
tmp[propertyName] = propertyValue //runtime values

Upvotes: 2

Sebastian Thees
Sebastian Thees

Reputation: 3391

class TmpClass {}
def tmp = new TmpClass()
tmp.metaClass.name = "value"

Upvotes: 2

YK S
YK S

Reputation: 3430

You can do the something like this:

class Student {
    private int StudentID;
    private String StudentName;

    void setStudentID(int pID) {
        StudentID = pID;
    }

    void setStudentName(String pName) {
        StudentName = pName;
    } 

    int getStudentID() {
        return this.StudentID;
    }

    String getStudentName() {
        return this.StudentName;
    }

    static void main(String[] args) {
        Student st = new Student();
        st.setStudentID(1);
        st.setStudentName("Joe");

        println(st.getStudentID());
        println(st.getStudentName());    
    } 
}

You need to have name as instance variable of type String. Also, You need to declare setter and getter methods to set and get the attribute also.

Upvotes: -1

Related Questions