JavaBean-平常笔记java
简单来讲,JavaBean是一种符合Java语法的可重用的组件(类)。
工具
Web应用程序中使用的JavaBean通常要知足以下要求:this
1)JavaBean成员有:方法(Method)、事件(Event)、属性(property)。spa
这里的属性是property而不是attribute。3d
1)attribute:表示状态,常认为字段(Field)是属性attribute。code
2)property:也表示状态,可是不是字段,是由类中属性的操做方法(getter/setter)来决定属性名称。orm
设置属性值:writableMethod:setter方法对象
获取属性值:readableMethod:getter方法blog
ex: setName/getName-->属性:name事件
setAge/getAge-->属性:age
若是数据类型为boolean,则为is方法。
2)内省机制(Introspector):操做(获取/设置)JavaBean中的方法/属性/事件。
使用static BeanInfo getBeanInfo(Class<?> beanClass)来获取指定字节码对象的JavaBean信息对象。
例如现有Person类,含属性(name,age)以及相应的getter和setter方法。
则可使用Beaninfo bi = Introspector.getBeanInfo(Person.class);获取到Person中的全部属性。
public class Person { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
经常使用方法:
1.PropertyDescriptor[ ] getPropertyDescriptors();获取JavaBean中的全部属性描述符。
public class IntrospectorDemo { public static void main(String[] args) throws IntrospectionException { BeanInfo beanInfo = Introspector.getBeanInfo(Person.class); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { //获得每个属性的描述器 System.out.println("属性名称:"+pd.getName()); System.out.println("属性类型:"+pd.getPropertyType()); System.out.println("set方法"+pd.getWriteMethod()); System.out.println("get方法"+pd.getReadMethod()); } } }
输出结果:
3)BeanUtils的使用
开发中,经常使用Apache common中的BeanUtils工具来操做JavaBean。
能够经过内省技术进行数据的封装,可是每一次写内省程序是一件很麻烦的事情,而且内省匹配也会有问题(例如一侧是String,一侧是int,还须要进行数据转化),
所以,内省(基于反射,方便操做javabean的API)封装form数据到javabean的代码,通常不本身编写,使用已经编写好的工具开发包BeanUtils开发包。
使用该工具前,须要提早去导入相应的jar包。
下载BeanUtils的jar :commons-beanutils 、commons-logging,须要同时下载这两个jar包,前者依赖后者。
这里就直接说明一些经常使用方法。
1.BeanUtils.setProperty(Bean对象,属性,属性的值);
2.BeanUtils.getProperty(Bean对象,属性);
3.BeanUtils.copyProperties(Bean对象,Bean对象);
属性拷贝:能够从JavaBean-->JavaBean, Map-->JavaBean(须要导common-collections包)。