A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 血马雄风 中级黑马   /  2015-8-26 10:12  /  229 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

个普通类符合JavaBean的规则,既可当作一个JavaBean来看,也可当作普通类来用。

JavaBean规则:
1、类的属性是private
2、类的属性符合JavaBean规则
3、类的属性由get和set方法获取和设置

class Person{             //bean class
    private String name;
    private int age;
   
    public BeanClass(String name, int age){
        this.name = name;
        this.age = age;
    }
    public String getName(){ return name;}
    public int getAge(){ return age;}
   
    public void setName(String name){ this.name = name;}
    public void setAge(int age){ this.age = age;}   
}


//main
//属性描述符:
Person person = new Person("Yang" , 25);
String propertyName = "name";
PropertyDescriptor personPdesc = new PropertyDescriptor(propertyName, person.getClass());
Method methodGetName = personPdesc.getReadMethod();
Object retNameVal = methodGetName.invoke(person);

Method methodSetName = personPdecs.getWriteMethod();
methodSetName.invoke(persion, "JUN");


//内省器:复杂方法,不推荐
Person person = new Person("Yang" , 25);
String propertyName = "name";
BeanInfo beanInfo = Introspector.getBeanInfo(person.getClass());
PropertyDescriptor[] personPdescs = beanInfo.getPropertyDecriptors(); // All,not one
Object retNameVal = null;
for(PropertyDescriptor pd : personPdescs){  //需要逐一遍历
    if(pd.getName().equals(propertyName)){
        Method methodGetName = pd.getReadMethod();
        retNameVal = methodGetName.invoke(person);
    }   
}

//使用Beanutils工具:下载相关包,并将包拷贝到工程下,右键-build path

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马