如何在列表中找到类<! - ? - >的名称

时间:2013-02-18 09:34:27

标签: java struts2 generic-list

我有一个Struts2 Action类

java.util.List list;

的getter / setters

但我不知道它的通用类型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
       }
    }
 } 

3 个答案:

答案 0 :(得分: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);
    }
}

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

答案 1 :(得分: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%确定它是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 
}  

答案 2 :(得分: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
 }
}