日期:2014-05-20 浏览次数:20619 次
public void get(List<?> list) {
}
//我想要在方法里遍历泛型?的所有域,因为list是动态传入,泛型不定,所以我得用反射来写,但是下面我就不知道怎么写了,不知道怎么处理这泛型,大牛帮忙
Type type = list.getClass().getGenericSuperclass();
//或这个
Type[] types = list.getClass().getGenericInterfaces();
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
class Person{
private int id;
private int age;
public Person(int id, int age) {
super();
this.id = id;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class ListTest {
public static <T> void get(List<T> list) throws Exception {
if(list==null
------解决方案--------------------
list.size()==0){
System.out.println("Null");
}else{
T t=list.get(0);
Field[] fields=t.getClass().getDeclaredFields();
for(Field f:fields){
f.setAccessible(true);
System.out.println(f.getName()+" "+f.get(t));
}
}
}
public static void main(String[] args) throws Exception {
List<Person> list=new ArrayList<Person>();
list.add(new Person(1, 2));
get(list);
}
}