int ageva l = (Integer) agermt.invoke(obj, null);
System.out.println("name = "+val);
System.out.println("age = "+ageva l);
}
@Test
public void test2() throws Exception{
BeanInfo bi = Introspector.getBeanInfo(Person.class);
PropertyDescriptor[] pd = bi.getPropertyDescriptors();
for (PropertyDescriptor pds : pd) {
System.out.println(pds.getName());
}
}
}
test运行结果:
name = jack
age = 20
test2()运行结果:所有属性:
age
class
name
任何一个JavaBean都有一个class属性,来自于Object类。所以包含class属性。
三、BeanUtils框架/工具(APACHE开源组织开发)
javaBean类:
[java]
package com.xiaohui.javabean;
import java.util.Date;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.xiaohui.javabean;
import java.util.Date;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
操作bean类的BeanUtils框架工具类代码
[java]
package com.xiaohui.javabean;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
public class Demo2 {
/**
* @param args
* @throws Exception
* @throws IllegalAccessException
*/
public static void main(String[] args) throws Exception {
Student s = new Student();
BeanUtils bu = new BeanUtils();
//向BeanUtils框架注册自己的转换器(String -> Date)
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class arg0, Object arg1) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse((String) arg1);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}}, java.util.Date.class);
bu.setProperty(s, "name", "小青");
bu.setProperty(s, "age", "20");
bu.setProperty(s, "birthday", "1992-02-05");
String nameva l = bu.getProperty(s, "name");
System.out.println("name = "+nameva l);
String ageva l = bu.getProperty(s, "age");
System.out.println("age = "+ageva l);
String bitVal = bu.getProperty(s, "birthday");
System.out.println("birthday = "+bitVal);
}
}
package com.xiaohui.javabean;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
impor