2012-11-16 23 views
0

我得到一个固定大小的数组,例如20个。任何优化的技术来设置bean中的数组值?

我必须在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个条件..性能问题..

任何优化技术赞赏...预先

谢谢...

+0

它是一个性能问题还是你不喜欢它?这似乎不太可能是你经常设置它,以至于它实际上是如何优化的。不要优化,直到你需要。 –

+0

为什么你在那里使用那个循环(和所有的条件检查)? –

+0

你根本不应该使用循环。您应该只有一行中有20条语句直接访问数组中的正确元素。 – jahroy

回答

2

一种方法是:

试试这个::

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

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

+0

感谢您的早期回应..这也是相当不错.. –

+1

这是一个比你选择的更好的答案。 – jahroy

+0

@jahroy感谢纠正我.. –

-1

U可以使用开关而不是这些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; 
      .... 
      .... 
    } 
} 
+0

谢谢..我真的没有这个想法使用开关..它真的很棒... –

+0

如果你觉得它有用,你可以接受答案 –

+0

我会..但至少我必须等待5到10分钟接受答案..所以我在等待.. –

1

另一种设置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 + "]"; 
     } 


    } 
}