在 bean 中设置数组值的任何优化技术



我得到一个固定大小为 20 的数组。

我必须在 bean 属性中设置每个数组元素,所以我的 bean 有 20 个属性。

这是我目前的方法:

Object[] record = { "0", "1", "2", ...."19" };
for (int j = 0; j < record.length; j++) {
    if (j == 0) {
        bean.setNo((String) record[j]);
    }
    if (j == 1) {
        bean.setName((String) record[j]);  
    }
    if (j == 2) {
        bean.setPhone((String) record[j]);  
    }
    // so on and so forth...
}

这就是我从数组中设置 bean 的每个属性的方式。

这里我在数组中有 20 个元素。

因此,要设置第 20 个元素,它正在检查 20 个条件。性能问题..

任何优化的技术都值得赞赏...

提前感谢...

一种方法是:

试试这个::

     Object[] record = BeanList.get(i);
     int j = 0;
     bean.setNo((String) record[j++]);
     bean.setName((String) record[j++]);  
     bean.setPhone((String) record[j++]);
.

..................................

另一种设置 bean 值的方法。这需要commons-beanutils.jar作为依赖关系。

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilsTest {
    // bean property names
    private static String[] propertyNames = { "name", "address" };
    public static void main(String[] args) throws IllegalAccessException,
            InvocationTargetException {
        // actual values u want to set
        String[] values = { "Sree", "India" };
        MyBean bean = new MyBean();
        System.out.println("Bean before Setting: " + bean);
        // code for setting values
        for (int i = 0; i < propertyNames.length; i++) {
            BeanUtils.setProperty(bean, propertyNames[i], values[i]);
        }
        // end code for setting values
        System.out.println("Bean after Setting: " + bean);
    }
    public static class MyBean {
        private String name;
        private String address;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        @Override
        public String toString() {
            return "MyBean [address=" + address + ", name=" + name + "]";
        }

    }
}

您可以使用 Switch 而不是这些 if 语句

for( int j =0; j < record.length; j++) {
     switch (j){
           case 1 :  bean.setNo((String) record[j]);break;
           case 2 :  bean.setNo((String) record[j]);break;
           ....
           ....
    }
}

相关内容

最新更新