如:
public class User { private String username;
private String password;
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}我在得到这个对像后,需要做一个循环取出所有的属性,不知道具体的代码应该如何来写!
public class User { private String username;
private String password;
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}我在得到这个对像后,需要做一个循环取出所有的属性,不知道具体的代码应该如何来写!
// TODO Auto-generated method stub
Field[] fs = User.class.getDeclaredFields();
for(int i = 0; i < fs.length; i ++){
System.out.println(fs[i].getName());
}
}显示结果为:
username
password
email现在又有一个新问题了,我怎么去使用这些属性的get方法呢?
如:知道有个username的属性,必然有一个getUsername的方法,这个方法应该怎样去实现呢?
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class ReadBean {
public static void readBean(Serializable theBean) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{ Class theBeanClass = theBean.getClass();
Method[] methods = theBeanClass.getDeclaredMethods();
for(int i = 0; i < methods.length; i++){
Method tmpMethod = methods[i];
String methodName = tmpMethod.getName();
if(methodName.indexOf("get") == 0){
tmpMethod.invoke(theBean, null);
}
}
}
}
的确能遍历完,调用的是前三个开头字母是"get"的方法来判断。
取到fields的名字再拼接get上去也是可以的,但是要把fields的第一个字母大写,有些麻烦,但我总觉得这两个办法总感觉不是太好,请高手指教。
System.out.println(tmpMethod.invoke(theBean, null));就能看出简单的输出数行数据