黑马程序员技术交流社区
标题:
Java内省,Javabean。
[打印本页]
作者:
于海生
时间:
2012-1-5 15:37
标题:
Java内省,Javabean。
本帖最后由 于海生 于 2012-1-6 09:21 编辑
什么是Java的内省,什么是Javabean,内省访问javabean通常有几种方式?请举例说明,详解.
作者:
胡家福
时间:
2012-1-5 16:08
内省(IntroSpector):主要对JavaBean进行操作。JDK提供了对JavaBean进行操作的一些API,这套API称为内省。
对JavaBean的简单内省操作:java.beans.PropertyDescriptor属性描述符类。new PropertyDescriptor(propertyName, class);
PropertyDescriptor类主要有方法getReadMethod()和getWriteMethod()
对JavaBean的复杂内省操作:java.beans.Introspector.getBeanInfo(class);这种方法复杂一些。
作者:
于海生
时间:
2012-1-5 16:30
例子呢??????
作者:
于海生
时间:
2012-1-6 09:06
结贴!
JavaBean 是一种JAVA语言写成的可重用组件。为写成JavaBean,类必须是具体的和公共的,并且具有无参数的构造器。JavaBean 通过提供符合一致性设计模式的公共方法将内部域暴露成员属性。众所周知,属性名称符合这种模式,其他Java 类可以通过自身机制发现和操作这些JavaBean 属性。
为了让程序员们更好的操作Java对象的属性,SUN公司开发了一套API,被业界内称为:内省;内省的出现有利于了对类对象属性的操作,减少了代码的数量。
内省访问JavaBean有两种方法:
一、通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 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;
}
}
复制代码
首先、是第一种方式,源码如下:
@Test
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
以下是通过第二种方法来操作Bean对象,源码如下:
@Test
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
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2