javaWeb之JavaBean总结

来源:互联网 发布:php 防止sql注入的方法 编辑:程序博客网 时间:2024/06/06 00:42

1.从狭义上来说,javaBean就是一个特殊的Java类,它里面只包含属性和set和get方法,不过JavaBean里面的set和get方法名必须是set或get+字段名。

2.每一个JavaBean中都隐含包含一个名为class的字段,该字段是从object类中继承而来。

3. 对JavaBean操作的两种方式,一种用sun公司自己提供的API, 称为内省(Introspector)API技术。另一种是开源组织Apache提供的BeanUtils框架。这一篇着重总结Introspector的使用方法。

通过内省技术操作JavaBean的两种方法:

第一种:通过PropertyDescriptor类操作Bean的属性(示例代码)

public void test1() throws Exception{
/*基于javaBean的内省(introspector)API*/
Student student = new Student();
//1.通过反射得到Student中字段name的属性描述对象pd
PropertyDescriptor pd = new PropertyDescriptor("name",Student.class);
//2.通过pd这个对象得到name属性的写方法。
Method method = pd.getWriteMethod();//得到的method实际上就相当于setName方法
//3.invoke的英文解释为调用,两个参数一个为对象名,另一个为名
method.invoke(student,"Berry");//这一句就相当于student.setName("Berry")
//4.通过pd这个对象得到name属性的读方法。
method=pd.getReadMethod();//得到的method实际上就相当于getName方法
//这一句相当于 String returnvalue =student.getName();
String returnvalue = (String) method.invoke(student, null);
System.out.println("returnvalue="+returnvalue);
}

 第二种:

通过Introspector类获得Bean对象的BeanInfo,然后通过BeanInfo获得属性描述器(PropertyDescriptor)的集合,然后依次遍历就可以得到每一个属性的名字。再通过属性描述器就可以用上面的方法来做。这种方法是用在(不知道目标类的属性名称的时候),如果对方已经暴露给我们类的字段名称了,在这样做就是多此一举。

public void test2() throws Exception{
//BeanInfo表示该Student对象所有的属性情况
BeanInfo bi = Introspector.getBeanInfo(Student.class);
//取得Student对象所有属性集合
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
for(PropertyDescriptor pd : pds){

System.out.println(pd.getName());//pd.getName()是属性值的名称


}
}






0 0