全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

Java 内省(Introspector)深入理解

Java 内省(Introspector)深入理解

一些概念:

  内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。

  JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得。

  例如类UserInfo :

package com.peidasoft.Introspector;

public class UserInfo {
  
  private long userId;
  private String userName;
  private int age;
  private String emailAddress;
  
  public long getUserId() {
    return userId;
  }
  public void setUserId(long userId) {
    this.userId = userId;
  }
  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getEmailAddress() {
    return emailAddress;
  }
  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }
  
}

  在类UserInfo中有属性 userName, 那我们可以通过 getUserName,setUserName来得到其值或者设置新的值。通过 getUserName/setUserName来访问 userName属性,这就是默认的规则。 Java JDK中提供了一套 API 用来访问某个属性的 getter/setter 方法,这就是内省。

  JDK内省类库:

  PropertyDescriptor类:

  PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:

      1. getPropertyType(),获得属性的Class对象;
      2. getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法;
      3. hashCode(),获取对象的哈希值;
      4. setReadMethod(Method readMethod),设置用于读取属性值的方法;
      5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。

  实例代码如下:

package com.peidasoft.Introspector;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class BeanInfoUtil { 
 
  public static void setProperty(UserInfo userInfo,String userName)throws Exception{
    PropertyDescriptor propDesc=new PropertyDescriptor(userName,UserInfo.class);
    Method methodSetUserName=propDesc.getWriteMethod();
    methodSetUserName.invoke(userInfo, "wong");
    System.out.println("set userName:"+userInfo.getUserName());
  }
 
  public static void getProperty(UserInfo userInfo,String userName)throws Exception{
    PropertyDescriptor proDescriptor =new PropertyDescriptor(userName,UserInfo.class);
    Method methodGetUserName=proDescriptor.getReadMethod();
    Object objUserName=methodGetUserName.invoke(userInfo);
    System.out.println("get userName:"+objUserName.toString());
  }
} 

  Introspector类:

  将JavaBean中的属性封装起来进行操作。在程序把一个类当做JavaBean来看,就是调用Introspector.getBeanInfo()方法,得到的BeanInfo对象封装了把这个类当做JavaBean看的结果信息,即属性的信息。

  getPropertyDescriptors(),获得属性的描述,可以采用遍历BeanInfo的方法,来查找、设置类的属性。具体代码如下:

package com.peidasoft.Introspector;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;


public class BeanInfoUtil {
    
  public static void setPropertyByIntrospector(UserInfo userInfo,String userName)throws Exception{
    BeanInfo beanInfo=Introspector.getBeanInfo(UserInfo.class);
    PropertyDescriptor[] proDescrtptors=beanInfo.getPropertyDescriptors();
    if(proDescrtptors!=null&&proDescrtptors.length>0){
      for(PropertyDescriptor propDesc:proDescrtptors){
        if(propDesc.getName().equals(userName)){
          Method methodSetUserName=propDesc.getWriteMethod();
          methodSetUserName.invoke(userInfo, "alan");
          System.out.println("set userName:"+userInfo.getUserName());
          break;
        }
      }
    }
  }
  
  public static void getPropertyByIntrospector(UserInfo userInfo,String userName)throws Exception{
    BeanInfo beanInfo=Introspector.getBeanInfo(UserInfo.class);
    PropertyDescriptor[] proDescrtptors=beanInfo.getPropertyDescriptors();
    if(proDescrtptors!=null&&proDescrtptors.length>0){
      for(PropertyDescriptor propDesc:proDescrtptors){
        if(propDesc.getName().equals(userName)){
          Method methodGetUserName=propDesc.getReadMethod();
          Object objUserName=methodGetUserName.invoke(userInfo);
          System.out.println("get userName:"+objUserName.toString());
          break;
        }
      }
    }
  }
  
}

    通过这两个类的比较可以看出,都是需要获得PropertyDescriptor,只是方式不一样:前者通过创建对象直接获得,后者需要遍历,所以使用PropertyDescriptor类更加方便。

  使用实例:

package com.peidasoft.Introspector;

public class BeanInfoTest {

  /**
   * @param args
   */
  public static void main(String[] args) {
    UserInfo userInfo=new UserInfo();
    userInfo.setUserName("peida");
    try {
      BeanInfoUtil.getProperty(userInfo, "userName");
      
      BeanInfoUtil.setProperty(userInfo, "userName");
      
      BeanInfoUtil.getProperty(userInfo, "userName");
      
      BeanInfoUtil.setPropertyByIntrospector(userInfo, "userName");      
      
      BeanInfoUtil.getPropertyByIntrospector(userInfo, "userName");
      
      BeanInfoUtil.setProperty(userInfo, "age");
      
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }

}

  输出:

get userName:peida
set userName:wong
get userName:wong
set userName:alan
get userName:alan
java.lang.IllegalArgumentException: argument type mismatch
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  at java.lang.reflect.Method.invoke(Method.java:597)
  at com.peidasoft.Introspector.BeanInfoUtil.setProperty(BeanInfoUtil.java:14)
  at com.peidasoft.Introspector.BeanInfoTest.main(BeanInfoTest.java:22) 

  说明:BeanInfoUtil.setProperty(userInfo, "age");报错是应为age属性是int数据类型,而setProperty方法里面默认给age属性赋的值是String类型。所以会爆出argument type mismatch参数类型不匹配的错误信息。

  BeanUtils工具包:

  由上述可看出,内省操作非常的繁琐,所以所以Apache开发了一套简单、易用的API来操作Bean的属性——BeanUtils工具包。

  BeanUtils工具包:下载:http://commons.apache.org/beanutils/ 注意:应用的时候还需要一个logging包 http://commons.apache.org/logging/

  使用BeanUtils工具包完成上面的测试代码:

package com.peidasoft.Beanutil;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import com.peidasoft.Introspector.UserInfo;

public class BeanUtilTest {
  public static void main(String[] args) {
    UserInfo userInfo=new UserInfo();
     try {
      BeanUtils.setProperty(userInfo, "userName", "peida");
      
      System.out.println("set userName:"+userInfo.getUserName());
      
      System.out.println("get userName:"+BeanUtils.getProperty(userInfo, "userName"));
      
      BeanUtils.setProperty(userInfo, "age", 18);
      System.out.println("set age:"+userInfo.getAge());
      
      System.out.println("get age:"+BeanUtils.getProperty(userInfo, "age"));
       
      System.out.println("get userName type:"+BeanUtils.getProperty(userInfo, "userName").getClass().getName());
      System.out.println("get age type:"+BeanUtils.getProperty(userInfo, "age").getClass().getName());
      
      PropertyUtils.setProperty(userInfo, "age", 8);
      System.out.println(PropertyUtils.getProperty(userInfo, "age"));
      
      System.out.println(PropertyUtils.getProperty(userInfo, "age").getClass().getName());
         
      PropertyUtils.setProperty(userInfo, "age", "8");  
    } 
     catch (IllegalAccessException e) {
      e.printStackTrace();
    } 
     catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    catch (NoSuchMethodException e) {
      e.printStackTrace();
    }
  }
}

  运行结果:

set userName:peida
get userName:peida
set age:18
get age:18
get userName type:java.lang.String
get age type:java.lang.String
8
java.lang.Integer
Exception in thread "main" java.lang.IllegalArgumentException: Cannot invoke com.peidasoft.Introspector.UserInfo.setAge 
on bean class 'class com.peidasoft.Introspector.UserInfo' - argument type mismatch - had objects of type "java.lang.String" 
but expected signature "int"
  at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2235)
  at org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:2151)
  at org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1957)
  at org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:2064)
  at org.apache.commons.beanutils.PropertyUtils.setProperty(PropertyUtils.java:858)
  at com.peidasoft.orm.Beanutil.BeanUtilTest.main(BeanUtilTest.java:38)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  at java.lang.reflect.Method.invoke(Method.java:597)
  at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2170)
  ... 5 more

  说明:

  1.获得属性的值,例如,BeanUtils.getProperty(userInfo,"userName"),返回字符串

  2.设置属性的值,例如,BeanUtils.setProperty(userInfo,"age",8),参数是字符串或基本类型自动包装。设置属性的值是字符串,获得的值也是字符串,不是基本类型。   3.BeanUtils的特点:
    1). 对基本数据类型的属性的操作:在WEB开发、使用中,录入和显示时,值会被转换成字符串,但底层运算用的是基本类型,这些类型转到动作由BeanUtils自动完成。
    2). 对引用数据类型的属性的操作:首先在类中必须有对象,不能是null,例如,private Date birthday=new Date();。操作的是对象的属性而不是整个对象,例如,BeanUtils.setProperty(userInfo,"birthday.time",111111);   

package com.peidasoft.Introspector;
import java.util.Date;

public class UserInfo {

  private Date birthday = new Date();
  
  public void setBirthday(Date birthday) {
    this.birthday = birthday;
  }
  public Date getBirthday() {
    return birthday;
  }   
}

package com.peidasoft.Beanutil;

import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import com.peidasoft.Introspector.UserInfo;

public class BeanUtilTest {
  public static void main(String[] args) {
    UserInfo userInfo=new UserInfo();
     try {
      BeanUtils.setProperty(userInfo, "birthday.time","111111"); 
      Object obj = BeanUtils.getProperty(userInfo, "birthday.time"); 
      System.out.println(obj);     
    } 
     catch (IllegalAccessException e) {
      e.printStackTrace();
    } 
     catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    catch (NoSuchMethodException e) {
      e.printStackTrace();
    }
  }
}

  3.PropertyUtils类和BeanUtils不同在于,运行getProperty、setProperty操作时,没有类型转换,使用属性的原有类型或者包装类。由于age属性的数据类型是int,所以方法PropertyUtils.setProperty(userInfo, "age", "8")会爆出数据类型不匹配,无法将值赋给属性。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


# Java内省Introspector  # 理解Java内省Introspector  # Java 内省introspector相关原理代码解析  # Java内省实例解析  # 浅谈Java内省机制  # 工具包  # 的是  # 这就是  # 遍历  # 主要用于  # 装进  # 类中  # 都是  # 不匹配  # 是一种  # 中有  # 转到  # 这两个  # 可以通过  # 希望能  # 还需要  # 可以看出  # 报错  # 谢谢大家  # 易用 


相关文章: 上海网站制作网站建设公司,建筑电工证网上查询系统入口?  logo在线制作免费网站在线制作好吗,DW网页制作时,如何在网页标题前加上logo?  无锡制作网站公司有哪些,无锡优八网络科技有限公司介绍?  长春网站建设制作公司,长春的网络公司怎么样主要是能做网站的?  济南专业网站制作公司,济南信息工程学校怎么样?  手机钓鱼网站怎么制作视频,怎样拦截钓鱼网站。怎么办?  南阳网站制作公司推荐,小学电子版试卷去哪里找资源好?  唐山网站制作公司有哪些,唐山找工作哪个网站最靠谱?  网站企业制作流程,用什么语言做企业网站比较好?  如何在阿里云虚拟机上搭建网站?步骤解析与避坑指南  建站主机与服务器功能差异如何区分?  岳西云建站教程与模板下载_一站式快速建站系统操作指南  赚钱网站制作软件,建一个网站怎样才能赚钱?是如何盈利的?  建站之星如何实现PC+手机+微信网站五合一建站?  制作网站建设的公司有哪些,网站建设比较好的公司都有哪些?  大连网站制作费用,大连新青年网站,五年四班里的视频怎样下载啊?  西安制作网站公司有哪些,西安货运司机用的最多的app或者网站是什么?  如何在阿里云通过域名搭建网站?  网站制作与设计教程,如何制作一个企业网站,建设网站的基本步骤有哪些?  ,网站推广常用方法?  如何在万网开始建站?分步指南解析  如何在阿里云虚拟服务器快速搭建网站?  如何用低价快速搭建高质量网站?  详解一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)  制作营销网站公司,淘特是干什么用的?  七夕网站制作视频,七夕大促活动怎么报名?  Android自定义listview布局实现上拉加载下拉刷新功能  如何快速辨别茅台真假?关键步骤解析  php json中文编码为null的解决办法  c# 服务器GC和工作站GC的区别和设置  广州网站制作的公司,现在专门做网站的公司有没有哪几家是比较好的,性价比高,模板也多的?  如何通过WDCP绑定主域名及创建子域名站点?  如何彻底删除建站之星生成的Banner?  如何配置IIS站点权限与局域网访问?  焦点电影公司作品,电影焦点结局是什么?  南宁网站建设制作定制,南宁网站建设可以定制吗?  高防网站服务器:DDoS防御与BGP线路的AI智能防护方案  最好的网站制作公司,网购哪个网站口碑最好,推荐几个?谢谢?  如何快速搭建高效可靠的建站解决方案?  如何在建站宝盒中设置产品搜索功能?  如何配置FTP站点权限与安全设置?  c# F# 的 MailboxProcessor 和 C# 的 Actor 模型  如何选择最佳自助建站系统?快速指南解析优劣  如何快速生成高效建站系统源代码?  宝华建站服务条款解析:五站合一功能与SEO优化设置指南  如何在阿里云购买域名并搭建网站?  建站之星北京办公室:智能建站系统与小程序生成方案解析  如何在橙子建站上传落地页?操作指南详解  北京制作网站的公司排名,北京三快科技有限公司是做什么?北京三快科技?  建站主机选购指南:核心配置优化与品牌推荐方案 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。