开发者

How to change the value of an attribute of a bean in list?

I am having a list of bean, now i want to change the value of an attribut开发者_如何学Pythone of all the beans in the list. For example:

class Person{
    String name;
    int age;
    String attrXYZ;

    /* accessors and mutators */
}

List<Person> lstPerson = getAllPersons();
//set the attribute attrXYZ of all persons in the list to 'undefined'

One way is to iterate the list and call setAttrXYZ ( 'undefined' ); this is what i am doing right now.

I would like to know is there any other approach of doing this.


Unfortunatly, even using reflection, you would have to iterate over your list. As a consequence, as far as I know, there is no other solution to that.


This is the advantage of dynamic languages like groovy, where you could do this as a one-liner:

myList.each{ it.setAttrXYZ ( 'undefined' ) }

In java, the shortest way is either to use java 5 loops or iterators:

for(MyBean bean : list){
    bean.setAttrXYZ ( "undefined" );
}

or

Iterator<MyBean> it = list.iterator();
while(it.hasNext()){
    it.next().setAttrXYZ("undefined");
}

(both of which is pretty much the same thing internally)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜