内省(Introspector)操作javabean的属性

1.首先查了一下什么是javabean

JavaBean是一个遵循特定写法的Java类,通常有一下几个特点

  • 这个Java类必须具有一个无参的构造函数
  • 属性必须私有化。
  • 私有化的属性必须通过public类型的方法暴露给其它程序,并且方法的命名也必须遵守一定的命名规范。

举例说明,下面就是一个简单的javabean类

 1 public class Teacher {
 2     
 3     private int age;
 4     
 5     private String name;
 6     
 7     private String sex;
 8     
 9     public Teacher(){
10         
11     }
12 
13     public int getAge() {
14         return age;
15     }
16 
17     public void setAge(int age) {
18         this.age = age;
19     }
20 
21     public String getName() {
22         return name;
23     }
24 
25     public void setName(String name) {
26         this.name = name;
27     }
28 
29     public String getSex() {
30         return sex;
31     }
32 
33     public void setSex(String sex) {
34         this.sex = sex;
35     }
36     
37 }

2.javabean的属性

JavaBean的属性可以是任意类型,并且一个JavaBean可以有多个属性。每个属性通常都需要具有相应的setter、 getter方法,setter方法称为属性修改器,getter方法称为属性访问器。
属性修改器必须以小写的set前缀开始,后跟属性名,且属性名的第一个字母要改为大写,例如,name属性的修改器名称为setName,password属性的修改器名称为setPassword。 
属性访问器通常以小写的get前缀开始,后跟属性名,且属性名的第一个字母也要改为大写,例如,name属性的访问器名称为getName,password属性的访问器名称为getPassword。 
一个JavaBean的某个属性也可以只有set方法或get方法,这样的属性通常也称之为只写、只读属性

 3.实验代码

Teacher类就是一个javabean,那么这个javabean中有多少个属性呢?

 1 package day4025;
 2 
 3 public class Teacher {
 4     
 5     private int age;
 6     
 7     private String name;
 8     
 9     private String sex;
10     
11     public Teacher(){
12         
13     }
14 
15     public int getAge() {
16         return age;
17     }
18 
19     public void setAge(int age) {
20         this.age = age;
21     }
22 
23     public String getName() {
24         return name;
25     }
26 
27     public void setName(String name) {
28         this.name = name;
29     }
30 
31     public String getSex() {
32         return sex;
33     }
34 
35     public void setSex(String sex) {
36         this.sex = sex;
37     }
38     
39     public String getYf(){
40         return null;
41     }
42     
43     public void setDd(String aaa){
44         String Dd = aaa;
45     }
46     
47 }

test1(获得所有属性)

 1     Teacher t = null;
 2     
 3     @Before
 4     public void testBefore(){
 5         t = new Teacher();
 6     }
 7     
 8     @Test
 9     public void test1() throws Exception{
10         //获得Teacher类的所有属性(包括从Object类继承的getClass属性)
11         BeanInfo info = Introspector.getBeanInfo(Teacher.class);
12         //获得属性描述器
13         PropertyDescriptor[] pds = info.getPropertyDescriptors();
14         for(PropertyDescriptor pd : pds){
15             System.out.println(pd.getName());
16         }
17     }

Junit测试结果

1 age
2 class
3 dd
4 name
5 sex
6 yf

age,name,sex这三个很好理解,那么class哪里来的呢,我们知道所有的类都继承自Object,我们看api文档可以找到Object类有一个getClass()方法,这里的class就是继承Object中的属性。dd和yf呢,这个和我们上面的话相对应一个JavaBean的某个属性也可以只有set方法或get方法,这样的属性通常也称之为只写、只读属性。所以说javabean的属性,是由getxxx()或setxxx决定的!

test2(去掉Object中继承的getClass()属性)

 1     @Before
 2     public void testBefore(){
 3         t = new Teacher();
 4     }
 5     @Test
 6     public void test2() throws Exception{
 7         //获得Teacher类的所有属性(去除Object类的属性)
 8         BeanInfo info = Introspector.getBeanInfo(Teacher.class,Object.class);
 9         //获得属性描述器
10         PropertyDescriptor[] pds = info.getPropertyDescriptors();
11         //获得所有属性的名字
12         for(PropertyDescriptor pd : pds){
13             System.out.println(pd.getName());
14         }
15     }

Junit测试结果

1 age
2 dd
3 name
4 sex
5 yf

test3(获取属性)

 1     Teacher t = null;
 2     
 3     @Before
 4     public void testBefore(){
 5         t = new Teacher();
 6     }
 7     @Test
 8     public void test3() throws Exception{
 9         //直接获得指定bean的指定属性
10         PropertyDescriptor pd = new PropertyDescriptor("age", Teacher.class);
11         //获得setAge()方法
12         Method method = pd.getWriteMethod();
13         method.invoke(t, 45);
14         //获得getAge()方法
15         Method method2 = pd.getReadMethod();
16         System.out.println(method2.invoke(t, null));
17     }

Junit测试结果

1 45

test4(得到指定属性的数据类型)

 1     Teacher t = null;
 2     
 3     @Before
 4     public void testBefore(){
 5         t = new Teacher();
 6     }
 7     public void test4() throws Exception{
 8         //获得Teacher类中age的数据类型
 9         PropertyDescriptor pd = new PropertyDescriptor("age", Teacher.class);
10         System.out.println(pd.getPropertyType());
11         
12     }

Junit测试结果

1 int

4.使用beanUtils操纵javabean

beanUtils是什么:BeanUtils工具是一种方便我们对JavaBean进行操作的工具,是Apache组织下的产品

使用beanUtils的第一步是导入jar包(Apache官方网站下载)

有了beanUtils后对javabean的操作就简单了

 1     Teacher t = null;
 2     
 3     @Before
 4     public void testBefore(){
 5         t = new Teacher();
 6     }
 7     @Test
 8     public void test5() throws Exception{
 9         //使用beanUtils的简单测试
10         BeanUtils.setProperty(t, "name", "happy");
11         System.out.println(t.getName());
12         
13     }

运行结果

1 happy

而且beanUtils会自动帮我们进行类型转换(但是转换只限于String向8种基础类型转换)

 1     Teacher t = null;
 2     
 3     @Before
 4     public void testBefore(){
 5         t = new Teacher();
 6     }
 7     @Test
 8     public void test6() throws Exception{
 9         //使用beanUtils的简单测试
10         BeanUtils.setProperty(t, "name", "happy");
11         BeanUtils.setProperty(t, "age", "22");
12         System.out.println(t.getName());
13         //这里可以看到,我们传进age的是字符串,但是没有报错,而且真正传进去的
14         //就是int类型,这是beanUtils自动帮我们转化。很方便
15         //但是需要注意的是,这种转化只支持8种数据类型
16         System.out.println(t.getAge());
17         
18     }

当我们想转向其他类型时就会报错

        当Teacher类有Date属性时    
    private Date birthday;
    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }


        测试代码    
    Teacher t = null;
    
    @Before
    public void testBefore(){
        t = new Teacher();
    }
    @Test
    public void test7() throws Exception{
        
        
        //这里会出错因为beanUtils不能自动将字符串转化成日期类型
        BeanUtils.setProperty(t, "birthday", "1997-09-11");
        System.out.println(t.getBirthday());
        //这时候就需要给jeanUtils注册日期转换器
        
    }

这时候我们就需要一个转换器

    Teacher t = null;
    
    @Before
    public void testBefore(){
        t = new Teacher();
    }
    @Test
    public void test8() throws IllegalAccessException, InvocationTargetException{
        
        //给beanUtils注册一个日期转换器
        ConvertUtils.register(new Converter(){

            @Override
            public Date convert(Class type, Object value) {
                // TODO Auto-generated method stub
                if(value == null){
                    return null;
                }
                if(!(value instanceof String)){
                    throw new ConversionException("只支持String类型的转换!");
                }
                String str = (String)value;
                if(str.trim().equals("")){
                    return null;
                }
                
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    return (Date) df.parse(str);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    throw new RuntimeException(e);
                }
                
            }
            
        }, Date.class);
        BeanUtils.setProperty(t, "birthday", "1997-05-15");
        System.out.println(t.getBirthday());
    }

这时候程序就可以正常运行

Thu May 15 00:00:00 CST 1997

当然有的转换器Apache已经帮我们写好了Date的转换器其实就有

    Teacher t = null;
    
    @Before
    public void testBefore(){
        t = new Teacher();
    }
    public void test9() throws Exception{
        
        ConvertUtils.register(new DateLocaleConverter(), Date.class);
        //这里会出错因为beanUtils不能自动将字符串转化成日期类型
        BeanUtils.setProperty(t, "birthday", "1997-09-11");
        System.out.println(t.getBirthday());
        //这时候就需要给jeanUtils注册日期转换器
        
    }

运行结果一样

Thu Sep 11 00:00:00 CST 1997

那为什么我们要自己写呢,因为Apache写的有些转换器代码不健壮,当我们给的字符串为空(str=“”)时,会报错,但是在现实中,输入的日期为空的情况肯定是存在的,所以我们转换日期的时候就需要自己写转换器了。

猜你喜欢

转载自www.cnblogs.com/Vamps0911/p/10769190.html
今日推荐