package reflect;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
/*
* 操作javabean
* 可以当作普通类处理(有时需要拼类名)
* 使用JDK的内省处理
* 使用Apache的BeanUtils工具处理
*/
public class IntroSpectorTest {
public static void main(String[] args) throws Exception {
User user = new User("zhangsan","admin");
String propertyName = "userName";
//使用内省操作javabean
//不是用内省的话,要先将userName首字母大写-->添加get-->拿到Method
//使用内省
//属性描述符
PropertyDescriptor pd1 = new PropertyDescriptor(propertyName, user.getClass());
//内省省略了首字母大写-->添加get-->这些步骤
Method methodGetUserName = pd1.getReadMethod();
Object retVal = methodGetUserName.invoke(user);
System.out.println(retVal);
//使用内省设置值
Method methodSetUserName = pd1.getWriteMethod();
methodSetUserName.invoke(user,"lisi");
System.out.println(user.getUserName());
//使用BeanUtils工具操作javabean
//这里要注意使用BeanUtils工具操作javabean时,javabean必须是public的类
BeanUtils.setProperty(user, "passWord","123456");
System.out.println(BeanUtils.getProperty(user, "passWord"));
//BeanUtils工具操作javabean时操作的属性是对象时,还可以链式级联操作
BeanUtils.setProperty(user, "date.time","111");
System.out.println(BeanUtils.getProperty(user, "date.time"));
//BeanUtils这个类setProperty设置的参数和getProperty返回的参数都是字符串
//都是会内部转换,但有的时候转的可能不准确,就可以用另外一个类,属性是什么类型
//get和set就是什么类型
PropertyUtils.setProperty(user, "age", 10);
System.out.println(PropertyUtils.getProperty(user, "age"));
}
}
package reflect;
import java.util.Date;
public class User {
public User(String userName, String passWord) {
super();
this.userName = userName;
this.passWord = passWord;
}
private Date date = new Date();
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
private String userName;
private String passWord;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}