JavaBean BeanUtils

IntroSpector-->JavaBean-->符合特殊规则的类

类中的属性对象都是可以用 set get方法来修改和获取值 注意
类型 get()_____________有返回值____不接受参数
void set(参数)_________没有返回值____接收参数

JavaBean中类的属性是根据方法推断出的

内省:
PropertyDescriptor类的应用
通过符合规则的JavaBean类和属性名,反射方法,从而得到获取和修改该属性名的值的方法,调用invoke调用方法
需要注意的是,为了使程序达到更好的复用性,应该将代码重构,将常用的代码块包装成为方法
包装时类应该采用Object类达到跟好的复用性

PropertyDescriptor pd = new PropertyDescriptor(属性名,类);
Method methodGet = pd.getReadMethod();
methodGet.invoke()

!!!注意JavaBean类 应该为public的 否则BeanUtils不能读取和修改里面的数据

 

apache开源jar下载地址

http://www.apache.org/dist//

 

测试
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.beanutils.BeanUtils;

public class TestBean {

    public static void main(String[] args) throws Exception{
        Point1 p1 = new Point1(1,2);
        Point1 p2 = new Point1(4,6);
       
        //System.out.println(p1.getX());
        String strname = "x";

        Object retval = getProperty(p1, strname);
        System.out.println(retval);
        int val = 7;
        setProperty(p1, strname, val);
       
        System.out.println(BeanUtils.getProperty(p1, strname));
       
        BeanUtils.setProperty(p1, strname, "10");   
        System.out.println(p1.getX());
    }

    public static void setProperty(Object p1, String strname, Object val)
            throws IntrospectionException, IllegalAccessException,
            InvocationTargetException {
        PropertyDescriptor pd2 = new PropertyDescriptor(strname,p1.getClass());
        Method methodSetX = pd2.getWriteMethod();
        methodSetX.invoke(p1,val);
       
       
    }

    public static Object getProperty(Object p1, String strname)
            throws IntrospectionException, IllegalAccessException,
            InvocationTargetException {
        PropertyDescriptor pd = new PropertyDescriptor(strname,p1.getClass());
       
        Object retval=null;
        Method methodGetX = pd.getReadMethod();
                retval = methodGetX.invoke(p1);
/*
        BeanInfo beanInfo = Introspector.getBeanInfo(p1.getClass());
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        for(PropertyDescriptor pd3:pds){
            if(pd3.getName().equals("strname")){
               
                break;
            }
        }
*/   
        return retval;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值