POJO
public class Student {
private String name;
private int age;
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getAbc(){
return 10;
}
}
内省
- Introspector构建一个BeanInfo对象。
- BeanInfo将一个类的所有属性进行了封装
- 获取属性描述器
PropertyDescriptor[] pds = bf.getPropertyDescriptors();
- PropertyDescriptor对象:
1. Method getReadMethod()
获得应该用于读取属性值的方法。
2. Method getWriteMethod()
获得应该用于写入属性值的方法。
public class 内省 {
@Test
public void test1() throws Exception {
BeanInfo bf = Introspector.getBeanInfo(Student.class);
PropertyDescriptor[] pds = bf.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
System.out.println(pd.getName());
}
}
@Test
public void test2() throws Exception {
Student stu = new Student();
PropertyDescriptor pd = new PropertyDescriptor("name", Student.class);
Method setter = pd.getWriteMethod();
setter.invoke(stu, "tom");
Method getter = pd.getReadMethod();
System.out.println(getter.invoke(stu, null));
}
@Test
public void test3() throws Exception {
Student stu = new Student();
PropertyDescriptor pd = new PropertyDescriptor("age", Student.class);
Method setter = pd.getWriteMethod();
setter.invoke(stu, 18);
Method getter = pd.getReadMethod();
System.out.println(getter.invoke(stu, null));
}
}
BeanUtils 的封装使用
public class BeanUtil {
@Test
public void test1() throws Exception{
Student stu = new Student();
BeanUtils.setProperty(stu, "name", "张三");
String s = BeanUtils.getProperty(stu, "name");
System.out.println(s);
}
@Test
public void test2() throws Exception{
Student stu = new Student();
BeanUtils.setProperty(stu, "age", "18");
String s = BeanUtils.getProperty(stu, "age");
System.out.println(s);
}
@Test
public void test3() throws Exception{
Student stu = new Student();
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.setProperty(stu, "birthday", "1990-11-12");
String s = BeanUtils.getProperty(stu, "birthday");
System.out.println(s);
}
@Test
public void test4() throws Exception{
Student stu = new Student();
ConvertUtils.register(new Converter() {
public Object convert(Class type, Object value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if(value instanceof String){
String v = (String) value;
try {
return sdf.parse(v);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
return null;
}
}, Date.class);
BeanUtils.setProperty(stu, "birthday", "1995-11-12");
String s = BeanUtils.getProperty(stu, "birthday");
System.out.println(s);
}
@Test
public void test5() throws Exception{
Map m = new HashMap();
m.put("name", "张三");
m.put("age", "18");
m.put("birthday", "1992-05-12");
Student stu = new Student();
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.populate(stu, m);
System.out.println(stu.getName());
}
}