黑马程序员-JavaBean
1. 内省(Introspector)
什么是内省?
--内省是Java对JavaBean类属性、事件的一种缺省处理方法。
--内省的出现有利于对类对象属性的操作,减少了代码的数量。
JDK内省类库
--PropertyDescriptor类:表示JavaBean类通过存储器导出一个属性。主要方法有:
1. getPropertyType(),获得属性的class对象;
2. getReadMethod(),获得用于读取属性值的方法;
3. getWriteMethod(),获得用于写入属性值的方法;
4. hashCode(),获取对象的哈希值;
5. setReadMethod(Method readMethod),设置用于读取属性值的方法;
6. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
内省访问JavaBean的两种方法:
--通过Introspector类获得Bean对象的BeanInfo,然后通过BeanInfo来获取属性的描述器(PertyDescriptor),通过这个属性描述器就可以获取某个属性对应的getter/setter方法,然后通过反射机制来调用这些方法。
--通过PropertyDescriptor来操作Bean对象。
以student类为例:
以student类为例:
public class Student {
private String name;//字段
public String getXxx(){//读方法
return "xx";
}
public String setXxx(){//写方法
return "xx";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
方法一:
public void test() throws Exception{
Student student = new Student();
//1.通过Introspector来获取bean对象的beaninfo
BeanInfo bif = Introspector.getBeanInfo(Student.class);
//2.通过beaninfo来获得属性描述器(propertyDescriptor)
PropertyDescriptor pds[] = bif.getPropertyDescriptors();
//3.通过属性描述器来获得对应的get/set方法
for(PropertyDescriptor pd:pds){
//4.获得并输出字段的名字
System.out.println(pd.getName());
//5.获得并输出字段的类型
System.out.println(pd.getPropertyType());
if(pd.getName().equals("name")){
//6.获得PropertyDescriptor对象的写方法
Method md = pd.getWriteMethod();
//7.执行写方法
md.invoke(student, "Lou_Wazor");
}
}
//8.输出所赋值字段的值
System.out.println(student.getName());
}
执行结果为:
class
class java.lang.Class
name
class java.lang.String
xxx
class java.lang.String
Lou_Wazor
方法二:
方法二:
public void test01()throws Exception{
Student st = new Student();
//1.通过构造器来创建PropertyDescriptor对象
PropertyDescriptor pd = new PropertyDescriptor("name", Student.class);
//2.通过该对象来获得写方法
Method method = pd.getWriteMethod();
//3.执行写方法
method.invoke(st, "Lou_Wazor");
//4.输出对象字段的值
System.out.println(st.getName());
//5.通过对象获得读方法
method = pd.getReadMethod();
//6.执行读方法并定义变量接受其返回值并强制塑形
String name = (String) method.invoke(st, null);
//7.输出塑形后的值
System.out.println(name);
}
执行结果为:
Lou_Wazor
Lou_Wazor
2. JavaBean
JavaBean是一种特殊的类
--主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合命名规则。
JavaBean的使用
--如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object)。方法比较少,这些信息存储在类的私有变量中,通过set()、get()获得。

浙公网安备 33010602011771号