Java基础加强之内省(introspector)

l      为什么要学内省?

l      开发框架时,经常需要使用java对象的属性来封装程序的数据,每次都使用反射技术完成此类操作过于麻烦,所以sun公司开发了一套API,专门用于操作java对象的属性。

l      什么是Java对象的属性和属性的读写方法?

l      内省访问JavaBean属性的两种方式:

l      通过PropertyDescriptor类操作Bean的属性

l      通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法。

l       

l       

l       

l       

l       

l      请使用sun内省api得到某一个bean的所有属性,并操作bean的其中一个属性(给属性赋值,以及得到属性的值) ,

 

     packagecn.csdn.java.introspector;

 

import java.beans.BeanInfo;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;

 

import org.junit.Test;

 

public class PersonBean {

 

    /**

     * introspector

     */

    public staticvoid main(String[] args) {

       // TODOAuto-generated method stub

 

    }

/* 

    一般的做法是通过类 Introspector来获取某个对象的 BeanInfo 信息,

    然后通过 BeanInfo来获取属性的描述器( PropertyDescriptor )

    通过这个属性描述器就可以获取某个属性对应的 getter/setter方法,

    然后通过反射机制来调用这些方法

*/

    //获取Person bean的属性

    public voidtest() throws Exception{

       BeanInfobi=Introspector.getBeanInfo(Person.class);

       PropertyDescriptor[] pds=

              bi.getPropertyDescriptors();

       for(PropertyDescriptorpd:pds){

           Stringname=pd.getName();

           System.out.println(name);

          

       }

    }

   

    //获取Person name的属性赋值

    @Test

       public voidtest1() throws Exception{

           Person p= new Person();

           BeanInfobi=Introspector.getBeanInfo(Person.class);

           PropertyDescriptor[] pds=

                   bi.getPropertyDescriptors();

           for(PropertyDescriptorpd:pds){

              Stringname=pd.getName();

              if(name.equals("name")){

                   Method m =pd.getWriteMethod();

                   m.invoke(p, "童话");

              }

             

             

           }

           System.out.println(p.getName());

       }

    //通过PropertyDescriptor操作bean的属性

    @Test

    public voidtest2() throws Exception{

       Person p =new Person();

       PropertyDescriptorpd= new PropertyDescriptor("name", p.getClass());

        Method m =pd.getWriteMethod();

        m.invoke(p, "天使的翅膀");

        System.out.println(p.getName());

    }

   

    public voidtest3() throws Exception{

       Person p =new Person();

       p.setName("联系");

       PropertyDescriptorpd= new PropertyDescriptor("name", p.getClass());

        Method m =pd.getReadMethod();

        String str=(String)m.invoke(p, null);

        System.out.println(str);

    }

   

   

   

}

 

 

l      .请使用beanUitls框架操作bean的属性,然后会自定义转换器

 

packagecn.csdn.java.introspector;

 

importjava.lang.reflect.InvocationTargetException;

import java.util.Date;

importjava.text.SimpleDateFormat;

 

importorg.apache.commons.beanutils.*;

importorg.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import org.junit.Test;

 

publicclass Beautils {

 

    /**

     * 自定义转换器

     */

   

    @Test

    publicvoid test()throws Exception{

        Person p =new Person();

        BeanUtils.setProperty(p,"name","刘德华");

        System.out.println(p.getName());

    }

    //beanutils工具对基本数据类型可以自动转换类型

    @Test

    publicvoid test1()throws Exception{

        ConvertUtils.register(new Converter(){

           /*自定义转换器*/

            @Override

            public Object convert(Classtype, Object value) {

                if(value==null){

                    returnnull;

                }

                if(!(valueinstanceof String)){

                    thrownew ConversionException("只能转String数据");

                }

                Strings=(String)value;

               

                if(s.trim().equals("")){

                    returnnull;

                }

               

                SimpleDateFormatsdf=new SimpleDateFormat("yyyy-MM-dd");

                try {

                    Dated=sdf.parse(s);

                    return d;

                } catch (Exception e) {

                    //TODO Auto-generatedcatch block

                    thrownew ConversionException("转换错误");

                }          

            }      

               

           

           

        }, Date.class);

        String name="张三";

        String age="23";

        Stringbirthday="    ";

       

        Person p=new Person();

        BeanUtils.setProperty(p,"name",name);

        BeanUtils.setProperty(p,"age",age);

        BeanUtils.setProperty(p,"birthday",birthday);

       

        System.out.println(p.getName()+"..."+p.getAge()+"...");

    }

    //使用beanUtils中的转换器完成数据转换

        @Test

        publicvoid test3()throws Exception{

           

            ConvertUtils.register(newDateLocaleConverter(), Date.class);

           

            Personp=new Person();

            BeanUtils.setProperty(p,"birthday","  ");

            //System.out.println(p.getBirthday());

           

        }

   

   

 

}

 

/*Beanutils工具包的常用类:

BeanUtils

PropertyUtils

ConvertUtils.regsiter(Converter convert, Classclazz)

自定义转换器*/

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值