我有一个Struts2 Action类
有java.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
}
}
}
答案 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
}
}