JAVA循环获取值

2024-10-31 21:17:45
推荐回答(2个)
回答1:

这个只能先把实体放到list里面,然后遍历就一次输出了。
List countList=new ArrayList();
countList.add(one);
...
countList.add(ten);
for(int i=0;i test = countList.get(i);
}

回答2:

采用java反射机制,遍历这个对象的所有get方法就可以
代码如下:
public class User {
private int age;
private String name;
private int sex;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
User(int age,int sex,String name){
this.age=age;
this.sex=sex;
this.name=name;
}

public static void main(String[] args) {
User u=new User(20, 1, "test");
Class c=u.getClass();
Method[] ms=c.getDeclaredMethods();
for(Method m:ms){
String name=m.getName();
if(name.startsWith("get")){
try {
Object r=m.invoke(u, null);
System.out.println(r);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}