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              

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值