1

我有一个 Struts2 Action 类

有getter/setterjava.util.List list;

但我不知道它的泛型List<?> list;

我这里有代码:

 public class Test
 {
    private List list;

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public String execute()throws Exception
    {
       for(int i=0;i<list.size();i++)
       {
           //how can print here list
           // in this situation i have List<Detail> list
           // filed is id ,username,password
           // but i want to print dynamically get class name and then filed name and then print list
       }
    }
 } 
4

3 回答 3

1

首先,您应该使该方法成为泛型方法,而不仅仅是使用 List。大致如下

public void parseList(List<T> list) {
    for (T list_entry : list) {
        System.out.println("File name: "+list_entry.getClass());
        System.out.println("List entry: " + list_entry);
    }
}

我意识到这对实际打印文件名没有多大帮助,但它确实可以帮助您从列表中获取对象的运行时类。

于 2013-02-18T09:41:03.647 回答
0

List一个通用类。但是你应该知道你在这个泛型类中使用了什么类型。如果你List在循环中使用(你的情况),for那么你应该写

for(Object o: list){
  if (o instanceof Detail){ //you can omit it if you 100% sure it is the Detail
   Detail d = (Detail)o; //explicitly typecast 
   //print it here 
  }
}  

但最好将list属性专门化以 100% 确定它是Details 列表

private List<Detail> list;

public List<Detail> getList() {
    return list;
}

public void setList(List<Detail> list) {
    this.list = list;
}

那么你可以使用

for(Detail d: list){
   //print it here 
}  
于 2013-02-18T12:19:55.447 回答
0

作为之前发布的答案,您可以使用“for each”循环:

for(Object element : list) {
 System.out.println("Class of the element: " + element.getClass());
 // If you want to do some validation, you can use the instanceof modifier
 if(element instanceof EmployeeBean) {
  System.out.println("This is a employee");
  // Then I cast the element and proceed with operations
  Employee e = (Employee) element;
  double totalSalary = e.getSalary() + e.getBonification();
 }
}

如果你想用“for while”循环来做:

for(int i = 0; i < list.size(); i++) {
 System.out.println("Element class: " + list.get(i).getClass());
 if (list.get(i) instanceof EmployeeBean) {
  EmployeeBean e = (EmployeeBean) list.get(i);
  // keep with operations
 }
}
于 2013-02-18T13:39:04.253 回答