java之PropertyUtils

1 java中如果不知道bean的类型或者不知道bean中的方法或属性时,无法给其赋值。但是java中有一个类可以在不知道bean的情况下也可以给其bean进行赋值和取值。那就是PropertyUtils类。该类可以对bean的属性(bean中要有属性的get和set方法)进行设值和取值。
设值通过:PropertyUtils.setProperty(Object bean,String shuxing,String value)
取值通过:PropertyUtils.getProperty(Object bean,String shuxing)
记住:PropertyUtils类是来自于:import org.apache.commons.beanutils.PropertyUtils;
如:
Users users=new Users();
try {
PropertyUtils.setProperty(users, "user_id", "admin");//设值
PropertyUtils.setProperty(users,"user_password","111111");//设值
System.out.println(PropertyUtils.getProperty(users,"user_id"));//取值
PropertyUtils.setProperty(users,"num",10);//属性是整形也满足条件。
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();

System.out.println(users.getUser_id()+"-"+users.getUser_password());
System.out.println(users.getNum());






其实PropertyUtils.setProperty(Object bean,String shuxing,String value)就相当于setXXX(String value)
和PropertyUtils.getProperty(Object bean,String shuxing)就相当于getXXX()方法


还有一个和PropertyUtils功能类似的,是BeanUtils。也是来自于:import org.apache.commons.beanutils.BeanUtils;


bean:
public class Users {


private String user_id;
private String user_password;
private List lists;

private int num;

public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public List getLists() {
return lists;
}
public void setLists(List lists) {
this.lists = lists;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String userId) {
user_id = userId;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String userPassword) {
user_password = userPassword;
}

}

猜你喜欢

转载自www.cnblogs.com/jpfss/p/12110838.html