【发布时间】:2015-01-05 22:56:53
【问题描述】:
基于此 Spring 教程:http://www.roseindia.net/tutorial/spring/spring3/ioc/springlistproperty.html 我遇到了问题。我使用 Spring 框架创建对象列表,但我想获取列表列表。从 ArrayList 转换为 ArrayList 是不可能的,所以我制作了自己的静态方法来做到这一点。我们有两个类:
学生:
public class Student {
private String name;
private String address;
//getters and setters
}
大学:
import java.util.List;
public class College {
private List<Object> list;
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
}
还有context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="Student" class="testing.Student">
<property name="name" value="Thomas"/>
<property name="address" value="London"/>
</bean>
<bean id="College" class="testing.College">
<property name="list">
<list>
<value>1</value>
<ref bean="Student"/>
<bean class="testing.Student">
<property name="name" value="John"/>
<property name="address" value="Manchester"/>
</bean>
</list>
</property>
</bean>
</beans>
这是我的主要方法:
public static void main(String[] args) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext(
"context.xml");
College college = (College) beanFactory.getBean("College");
}
我想在这里做的是通过从包含对象列表的大学对象接收它来制作通用的学生数组列表。这是我的解决方案:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
public class MainTest {
//This is my casting static method:
public static ArrayList<Student> castListToStudent(College college) {
ArrayList<Student> casted = new ArrayList<Student>();
Student s = null;
for (int i = 0; i < college.getList().size(); i++) {
if (college.getList().get(i) instanceof Student) {
s = (Student) college.getList().get(i);
casted.add(s);
}
}
return casted;
}
public static void main(String[] args) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext(
"context.xml");
College college = (College) beanFactory.getBean("College");
ArrayList<Student> list = castListToStudent(college);
for (Student s : list) {
System.out.println(s);
}
}
}
看起来它正在工作,但问题是 - 这是安全地将一个列表转换为另一个列表的最佳方式吗?
【问题讨论】:
-
我认为这在 Spring 4 中已经解决了。