【发布时间】:2016-04-16 16:40:01
【问题描述】:
我有一个接受对象的方法。对象是一个列表。该列表可以是任何类型。我想使用反射识别列表的类型并创建列表的实例并对其进行迭代并打印结果。
不同类型的列表
List<Customer> customerList = new ArrayList<Customer>();
List<Service> serviceList = new ArrayList<Service>();
List<Product> productList = new ArrayList<Product>();
接受列表的方法
public void printList(Object genericList){
// identify the type of list
// create the list object
// iterate over the list and print the values
}
【问题讨论】:
-
我有几个澄清问题: 1. 当您说“识别列表类型”时,您的意思是识别它是否是
ArrayList、LinkedList等,或者识别是否包含类型为Customer、Service、Product等。 2. 当printList()创建新列表时,是否必须与genericList为同一类?例如,如果genericList是ArrayList的实例,那么名为newList的变量是否可以是LinkedList的实例? 3. 当“迭代列表以打印值”时,您是否期望我们迭代newList或genericList?
标签: java