JAVA中的内省

为了让程序员们更好的操作Java对象的属性,SUN公司开发了一套API,被业界内称为:内省;内省的出现有利于了对类对象属性的操作,减少了代码的数量。

内省访问JavaBean有两种方法:

       一、通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法。

       二、通过PropertyDescriptor来操作Bean对象

接下来要对Student 类对象进行操作,Student类源码如下:

1 public class Student {
2
3 private String name;//字段
4  
5 public String getXxx(){//读方法
6  
7 return "xx";
8
9 }
10
11 public String setXxx(){//写方法
12  
13 return "xx";
14
15 }
16
17 public String getName() {
18
19 return name;
20
21 }
22
23 public void setName(String name) {
24
25 this.name = name;
26
27 }
28
29 }

首先、是第一种方式,源码如下:

    

 
   
1 @Test
2
3 public void test() throws Exception{
4
5 Student student = new Student();
6
7 // 1.通过Introspector来获取bean对象的beaninfo
8  
9 BeanInfo bif = Introspector.getBeanInfo(Student. class );
10
11 // 2.通过beaninfo来获得属性描述器(propertyDescriptor)
12  
13 PropertyDescriptor pds[] = bif.getPropertyDescriptors();
14
15 // 3.通过属性描述器来获得对应的get/set方法
16
17 for (PropertyDescriptor pd:pds){
18
19 // 4.获得并输出字段的名字
20
21 System.out.println(pd.getName());
22
23 // 5.获得并输出字段的类型
24
25 System.out.println(pd.getPropertyType());
26
27 if (pd.getName().equals( " name " )){
28
29 // 6.获得PropertyDescriptor对象的写方法
30
31 Method md = pd.getWriteMethod();
32
33 // 7.执行写方法
34
35 md.invoke(student, " Lou_Wazor " );
36
37 }
38
39 }
40
41 // 8.输出所赋值字段的值
42
43 System.out.println(student.getName());
44
45 }

执行结果为:

class

class java.lang.Class

name

class java.lang.String

xxx

class java.lang.String

Lou_Wazor

以下是通过第二种方法来操作Bean对象,源码如下:

 
   
1 @Test
2
3 public void test01() throws Exception{
4
5 Student st = new Student();
6
7 // 1.通过构造器来创建PropertyDescriptor对象
8
9 PropertyDescriptor pd = new PropertyDescriptor( " name " , Student. class );
10
11 // 2.通过该对象来获得写方法
12
13 Method method = pd.getWriteMethod();
14
15 // 3.执行写方法
16
17 method.invoke(st, " Lou_Wazor " );
18
19 // 4.输出对象字段的值
20
21 System.out.println(st.getName());
22
23 // 5.通过对象获得读方法
24
25 method = pd.getReadMethod();
26
27 // 6.执行读方法并定义变量接受其返回值并强制塑形
28
29 String name = (String) method.invoke(st, null );
30
31 // 7.输出塑形后的值
32
33 System.out.println(name);
34
35 }

执行结果为:

Lou_Wazor

Lou_Wazor              

以上为自省的一些知识点,希望大家互相交流,提出意见和问题,以便进行讨论学习。


转载于:https://www.cnblogs.com/H_Razor/archive/2011/02/28/1967178.html

猜你喜欢

转载自blog.csdn.net/weixin_34309435/article/details/93795395