java之PropertyUtils

本文介绍Java中BeanUtils和PropertyUtils类的功能与使用方法,重点讲解如何利用这两个类在不了解Bean具体类型的情况下,对Bean的属性进行设置和获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值