如何使用BeanUtils.populate方法將String []轉換爲ArrayList?它看起來像我可以使用ArrayConverter類,但我很難找到解釋如何做到這一點。如何使用BeanUtils.populate方法將String []轉換爲ArrayList <String>?
下面是一些測試代碼,我創建:
public class TestAction {
public static TestBean testPopulate() throws IllegalAccessException, InvocationTargetException {
HashMap<String, Object> map = new HashMap<String, Object>();
TestBean bean = new TestBean();
String[] names = {"teststring","testboolean","testinteger","testarray"};
String[] array = {"hi","bye"};
Object[] values = {"TEST","","100",array};
int i = 0;
while (i < names.length) {
String name = names[i];
map.put(name, values[i]);
i++;
}
BeanUtils.populate(bean, map);
return bean;
}
public static void main(String[] args) {
try {
TestBean bean = testPopulate();
System.out.println(bean.getTeststring() + " " + bean.getTestinteger() + " " + bean.getTeststring() + " " + bean.isTestboolean());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TestBean {
private String teststring;
private boolean testboolean;
private int testinteger;
private ArrayList<String> testarray;
public String getTeststring() {
return teststring;
}
public void setTeststring(String teststring) {
this.teststring = teststring;
}
public boolean isTestboolean() {
return testboolean;
}
public void setTestboolean(boolean testboolean) {
this.testboolean = testboolean;
}
public int getTestinteger() {
return testinteger;
}
public void setTestinteger(int testinteger) {
this.testinteger = testinteger;
}
public ArrayList<String> getTestarray() {
return testarray;
}
public void setTestarray(ArrayList<String> testarray) {
this.testarray = testarray;
}
}
我傳遞一個字符串[]類型期待它知道如何轉換爲ArrayList中,但它失敗。
好吧,我現在明白了。我將String []更改爲ArrayList,並且代碼沒有錯誤地運行。從String []轉換爲ArrayList 時,BeanUtils故意失敗。作爲Java中的HttpServletRequest類返回String或String []類型的後續問題,那麼是否強制我在我的bean中僅使用基本類型和String []類型? –
user2191540
2013-03-23 22:42:00
「HttpServletRequest」的哪個方法?它並不強迫你,但是,如果在bean中傳遞的數據類型是一個String [],那麼在你的bean中使用數組可能是有意義的,然後當它們轉換爲List對象時你需要。或者,做一些預處理。在將映射傳遞給BeanUtils.populate之前,請構建要使用的'List'對象,並將其放入映射中。 – dimo414 2013-03-23 22:54:59
啊...預處理是一個好主意,我會嘗試一下。感謝您的建議。 – user2191540 2013-03-23 23:42:52