2013-02-18 29 views
2

使用类我有一个Struts2的Action类的名称如何找到列表

存在的java.util.List list;

getter/setter方法,但我不知道它的泛型类型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 
     } 
    } 
} 

回答

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(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 
} 
} 
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); 
    } 
} 

我知道这并不能帮助这么多的实际打印的文件名,但它确实有助于您获得运行时类现身列表的对象的东西。

0

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

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%肯定它是Detail上榜

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 
}