BeanUtils简要描述

beanutils,顾名思义,是java bean的一个工具类,可以帮助我们方便的读取(get)和设置(set)bean属性值、动态定义和访问bean属性;

细心的话,会发现其实JDK已经提供了一个java.beans包,同样可以实现以上功能,只不过使用起来比较麻烦,所以诞生了apache commons beanutils;

看源码就知道,其实apache commons beanutils就是基于jdk的java.beans包实现的。

Java Bean

在介绍apache commons beanutils之前,很有必要先了解下javabean。

apache commons beanutils就是基于JavaBeans的设计命名规范来实现的,如下是一个简单的javabean示例:

/*
* File Name: Employee.java
* Description:
* Author: PiChen
* Create Date: 2017年5月29日
*/
package apache.commons.beanutils.example.pojo; import java.util.Date; /**
*
* @author PiChen
* @version 2017年5月29日
*/ public class Employee
{
private String firstName;
private String lastName;
private Date hireDate;
private boolean isManager;/**
* @return the firstName
*/
public String getFirstName()
{
return firstName;
} /**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName)
{
this.firstName = firstName;
} /**
* @return the lastName
*/
public String getLastName()
{
return lastName;
} /**
* @param lastName the lastName to set
*/
public void setLastName(String lastName)
{
this.lastName = lastName;
} /**
* @return the hireDate
*/
public Date getHireDate()
{
return hireDate;
} /**
* @param hireDate the hireDate to set
*/
public void setHireDate(Date hireDate)
{
this.hireDate = hireDate;
} /**
* @return the isManager
*/
public boolean isManager()
{
return isManager;
} /**
* @param isManager the isManager to set
*/
public void setManager(boolean isManager)
{
this.isManager = isManager;
} /**
* @return the fullName
*/
public String getFullName()
{
return firstName + " " + lastName;
} }

javabean一般有以下几个特性:

1、类必须是public访问权限,且需要有一个public的无参构造方法,之所以这样主要是方便利用Java的反射动态创建对象实例:

Class beanClass = Class.forName(className);
Object beanInstance = beanClass.newInstance();

2、由于javabean的构造方法是无参的,所以我们的bean的行为配置(即设置bean的属性值,方法对应行为,属性对应数据)不能在构造方法完成,取而代之的是通过一系列的set方法来设置属性值,通过setter方法,我们可以改变javabean呈现出来的行为和内部数据,这里的setter方法会按一定的约定来命名,如setHireDate、setName。。。

3、读取和设置bean属性值的命名约定,即getter方法和setter方法,不过这里需要特别注意boolean类型的约定,如下示例:

    private String firstName;
private String lastName;
private Date hireDate;
private boolean isManager;
public String getFirstName();
public void setFirstName(String firstName);
public String getLastName();
public void setLastName(String lastName);
public Date getHireDate();
public void setHireDate(Date hireDate);
public boolean isManager();
public void setManager(boolean manager);

4、并不是必须为每个属性提供setter和getter方法,我们可以只定义一个属性的getter方法而不定义setter方法,这样的属性一般是只读属性;

访问基本数据类型的Bean属性

简述:

  这类属性指的是Integer, Double, Float, boolean等,,,, 注意这里还包括String,其实像HashMap,ArrayList, 等属性都可以设置,只不过Map里面的键值对、List索引处的值无法通过这两个API访问,需要使用专门的API来处理,接下来将会介绍;

访问API:

调用示例:

/*
* File Name: Main.java
* Description:
* Author: PiChen
* Create Date: 2017年5月29日
*/
package apache.commons.beanutils.example.propertyaccess; import java.lang.reflect.InvocationTargetException; import org.apache.commons.beanutils.PropertyUtils; import apache.commons.beanutils.example.pojo.Employee; /**
*
* @author PiChen
* @version 2017年5月29日
*/ public class BasicPropertyAccess
{ /**
*
*
* @param args
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/ public static void main(String[] args)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
Employee employee = new Employee();
String firstName = (String) PropertyUtils.getSimpleProperty(employee, "firstName");
String lastName = (String) PropertyUtils.getSimpleProperty(employee, "lastName"); firstName = firstName == null ? "Pi" : "";
lastName = lastName == null ? "Chen" : ""; PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
PropertyUtils.setSimpleProperty(employee, "lastName", lastName); System.out.println(employee.getFullName());
} }

访问索引类型的Bean属性

简述:

  可索引的属性,如ArrayList, 数组等,可以通过下标索引来访问Bean属性的值, 同理可设置value;

访问API

调用示例

Bean:

package apache.commons.beanutils.example.pojo;

import java.util.List;

public class IndexedBean {
private List<Employee> employeeList;
private Integer[] intArr; /**
* @return the employeeList
*/
public List<Employee> getEmployeeList()
{
return employeeList;
} /**
* @param employeeList the employeeList to set
*/
public void setEmployeeList(List<Employee> employeeList)
{
this.employeeList = employeeList;
} /**
* @return the intArr
*/
public Integer[] getIntArr()
{
return intArr;
} /**
* @param intArr the intArr to set
*/
public void setIntArr(Integer[] intArr)
{
this.intArr = intArr;
}
}

调用example:

/*
* File Name: Main.java
* Description:
* Author: PiChen
* Create Date: 2017年5月29日
*/
package apache.commons.beanutils.example.propertyaccess; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.beanutils.PropertyUtils; import apache.commons.beanutils.example.pojo.Employee;
import apache.commons.beanutils.example.pojo.IndexedBean; /**
*
* @author PiChen
* @version 2017年5月29日
*/ public class IndexedPropertiesAccess
{ /**
*
*
* @param args
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/ public static void main(String[] args)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
// 初始工作
IndexedBean indexedBean = new IndexedBean();
List<Employee> employeeList = new ArrayList<Employee>();
Employee e1 = new Employee();
e1.setLastName("Chen");
Employee e2 = new Employee();
e2.setLastName("Wang");
employeeList.add(e1);
employeeList.add(e2);
indexedBean.setEmployeeList(employeeList);
indexedBean.setIntArr(new Integer[]{ 0, 1, 2 }); // API测试
int index0 = 0;
String name0 = "employeeList[" + index0 + "]";
Employee employee0 = (Employee) PropertyUtils.getIndexedProperty(indexedBean, name0);
System.out.println(employee0.getLastName()); int index1 = 1;
String name1 = "employeeList[" + index1 + "]";
Employee employee1 = (Employee) PropertyUtils.getIndexedProperty(indexedBean, name1);
System.out.println(employee1.getLastName()); Employee employee00 = (Employee) PropertyUtils.getIndexedProperty(indexedBean,"employeeList", 0);
Employee employee11 = (Employee) PropertyUtils.getIndexedProperty(indexedBean,"employeeList", 1);
System.out.println(employee00.getLastName());
System.out.println(employee11.getLastName()); Integer i = (Integer) PropertyUtils.getIndexedProperty(indexedBean,"intArr", 1);
System.out.println(i);
} }

访问Map映射类型的Bean属性

简述:

  常见的HashMap,TreeMap等,可以通过key来访问Bean属性值,同理可设置value;

访问API:

调用示例:

map bean:

/*
* File Name: MappedBean.java
* Description:
* Author: PiChen
* Create Date: 2017年5月29日
*/
package apache.commons.beanutils.example.pojo; import java.util.Map; /**
*
* @author PiChen
* @version 2017年5月29日
*/ public class MappedBean
{
private Map<String, Object> mapProperty; /**
* @return the mapProperty
*/
public Map<String, Object> getMapProperty()
{
return mapProperty;
} /**
* @param mapProperty the mapProperty to set
*/
public void setMapProperty(Map<String, Object> mapProperty)
{
this.mapProperty = mapProperty;
} }

使用example:

/*
* File Name: MapPropertyAccess.java
* Description:
* Author: PiChen
* Create Date: 2017年5月29日
*/
package apache.commons.beanutils.example.propertyaccess; import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.beanutils.PropertyUtils;
import apache.commons.beanutils.example.pojo.MappedBean; /**
*
* @author PiChen
* @version 2017年5月29日
*/ public class MapPropertyAccess
{ public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
MappedBean employee = new MappedBean();
Map<String, Object> map = new HashMap<String, Object>();
//employee.setMapProperty(map);
PropertyUtils.setSimpleProperty(employee, "mapProperty", map); PropertyUtils.setMappedProperty(employee, "mapProperty", "testKey1", "testValue1");
PropertyUtils.setMappedProperty(employee, "mapProperty(testKey2)", "testValue2"); System.out.println(employee.getMapProperty().get("testKey1"));
System.out.println(employee.getMapProperty().get("testKey2")); }
}

访问嵌套类型的Bean属性

简述:

  指的是对象内嵌套对象

访问API:

调用示例:

嵌套bean:

/*
* File Name: NestedBean.java
* Description:
* Author: PiChen
* Create Date: 2017年5月29日
*/
package apache.commons.beanutils.example.pojo; import java.util.List;
import java.util.Map; /**
*
* @author PiChen
* @version 2017年5月29日
*/ public class NestedBean
{ private List<Employee> listProperty;
private Map<String, Employee> mapProperty;
/**
* @return the listProperty
*/
public List<Employee> getListProperty()
{
return listProperty;
}
/**
* @param listProperty the listProperty to set
*/
public void setListProperty(List<Employee> listProperty)
{
this.listProperty = listProperty;
}
/**
* @return the mapProperty
*/
public Map<String, Employee> getMapProperty()
{
return mapProperty;
}
/**
* @param mapProperty the mapProperty to set
*/
public void setMapProperty(Map<String, Employee> mapProperty)
{
this.mapProperty = mapProperty;
}
}

使用example:

/*
* File Name: NestedPropertyAccess.java
* Description:
* Author: PiChen
* Create Date: 2017年5月29日
*/
package apache.commons.beanutils.example.propertyaccess; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import apache.commons.beanutils.example.pojo.Employee;
import apache.commons.beanutils.example.pojo.NestedBean; /**
*
* @author PiChen
* @version 2017年5月29日
*/ public class NestedPropertyAccess
{ public static void main(String[] args)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
Employee e = new Employee();
e.setLastName("Chen"); NestedBean nestedBean = new NestedBean(); List<Employee> list = new ArrayList<Employee>();
list.add(e); Map<String, Employee> map = new HashMap<String, Employee>();
map.put("testKey", e); nestedBean.setListProperty(list);
nestedBean.setMapProperty(map); String lastName = (String) PropertyUtils.getNestedProperty(nestedBean,
"mapProperty(testKey).lastName");
System.out.println(lastName);
String lastName2 = (String) PropertyUtils.getNestedProperty(nestedBean,
"listProperty[0].lastName");
System.out.println(lastName2);
}
}

访问所有类型的Bean属性

简述

  通过以上API的使用,我们了解了各类bean属性的访问方法,其实还有一种通用的方法,适用于各类bean属性类型;

访问API

使用示例,这里直接以嵌套类型属性为例

/*
* File Name: NestedPropertyAccess.java
* Description:
* Author: PiChen
* Create Date: 2017年5月29日
*/
package apache.commons.beanutils.example.propertyaccess; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import apache.commons.beanutils.example.pojo.Employee;
import apache.commons.beanutils.example.pojo.NestedBean; /**
*
* @author PiChen
* @version 2017年5月29日
*/ public class NestedPropertyAccess
{ public static void main(String[] args)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
Employee e = new Employee();
e.setLastName("Chen"); NestedBean nestedBean = new NestedBean(); List<Employee> list = new ArrayList<Employee>();
list.add(e); Map<String, Employee> map = new HashMap<String, Employee>();
map.put("testKey", e); nestedBean.setListProperty(list);
nestedBean.setMapProperty(map); String lastName2 = (String) PropertyUtils.getProperty(nestedBean,
"listProperty[0].lastName");
System.out.println(lastName2); PropertyUtils.setProperty(nestedBean, "listProperty[0].lastName", "Hello World");
System.out.println(nestedBean.getListProperty().get(0).getLastName());
}
}

参考资料

commons.apache.org/proper/commons-beanutils/javadocs/v1.9.3/apidocs/org/apache/commons/beanutils/package-summary.html

源码链接:

https://github.com/peterchenhdu/apache-commons-beanutils-example

Apache Commons Beanutils 一 (使用PropertyUtils访问Bean属性)的更多相关文章

  1. Apache Commons Beanutils 二 (动态Bean - DynaBeans)

    相关背景 上一篇介绍了PropertyUtils的用法,PropertyUtils主要是在不修改bean结构的前提下,动态访问bean的属性: 但是有时候,我们会经常希望能够在不定义一个Java类的前 ...

  2. 对于Java Bean的类型转换问题()使用 org.apache.commons.beanutils.ConvertUtils)

    在进行与数据库的交互过程中,由数据库查询到的数据放在 map 中,由 map 到 JavaBean 的过程中可以使用 BeanUtils.populate(map,bean)来进行转换 这里要处理的问 ...

  3. Apache Commons BeanUtils

    http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanut ...

  4. Apache Commons Beanutils 三 (BeanUtils、ConvertUtils、CollectionUtils...)

    前言 前面已经学习了Apache Commons Beanutils包里的PropertyUtils和动态bean,接下来将学习剩下的几个工具类,个人觉得还是非常实用的,特别是CollectionUt ...

  5. 关闭log4j 输出 DEBUG org.apache.commons.beanutils.*

    2016-03-23 10:52:26,860 DEBUG org.apache.commons.beanutils.MethodUtils - Matching name=getEPort on c ...

  6. Apache Commons Beanutils对象属性批量复制(pseudo-singleton)

    Apache Commons Beanutils为开源软件,可在Apache官网http://commons.apache.org/proper/commons-beanutils/download_ ...

  7. org.apache.commons.beanutils.BeanMap简单使用例子

    一.org.apache.commons.beanutils.BeanMap; 将一个java bean允许通过map的api进行调用, 几个支持的操作接口: Object get(Object ke ...

  8. org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils的copyProperties用法区别

    知识点 org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils都提供了copyProperties方法,作 ...

  9. org.apache.commons.beanutils.BeanUtils的常见用法

    import org.apache.commons.beanutils.BeanUtils BeanUtils1. public static void copyProperty(Object bea ...

随机推荐

  1. Java高级

    1.GC是什么?为什么要有GC? GC是垃圾收集的意思(Gabage Collection),内存处理是编程人员容易出现问题的地方,忘记或者错误的内存回收会导致程序或系统的不稳定甚至崩溃,Java提供 ...

  2. 49-Python 安装pythoncom库和pyHook

    这个直接用pip不行,所以借鉴了别人的方法: YTouchCoder 1. https://sourceforge.net/projects/pywin32/files/pywin32/ 这里面下载p ...

  3. 关于弹性布局的 flex-grow的用法和flex-shrink的用法

    1.首先 flex-grow设置在子项目上 2.flex-grow默认值为0,如果为值1的时候就会撑满 3.flex-grow还可以给其中的一个子元素单独设置,设置为2,其它的则为1或者2都可以,具体 ...

  4. javascript 新建实例对象

    在main js里面new 这样一个实例算怎么回事,如果不这么new, ToolBar里就会报错: Portal.gbl = { constants : new Portal.common.Const ...

  5. SQL Server 2008 R2 根据.asmx访问WebService

    .asmx 都是.Net 同系列,所以学习的时候会比较简单. 方法一: 步骤1.在浏览器打开.asmx地址可以到方法列表, 步骤2.点进方法列表会有SOAP调用的案例, 步骤3.SQL Server ...

  6. concurrent.futures模块(进程池/线程池)

    需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...

  7. ping内网一台虚拟机延时很大(hyper-v虚拟机)的解决办法

    问题现象: ping 内网一台虚拟机延时很大,不稳定,造成业务系统响应慢.查看服务器上各种资源都正常. 解决办法: 在物理机上找到和hyper-v绑定的那个网卡,把“虚拟机队列”禁用掉就好了,如下图: ...

  8. TaxonKit - A cross-platform and Efficient NCBI Taxonomy Toolkit

    https://github.com/0820LL/taxonkit Usage: https://bioinf.shenwei.me/taxonkit/usage/

  9. redis在游戏服务器中的使用初探(一) 环境搭建

    这里我们尝试在游戏服务器中的数据处理中使用redis 通过该系列文章能够学习 redis的基本操作 源码编译 客户端开源库的编译和使用 以及在游戏服务器中的缓存使用 作为初次摸索 尽量使得环境简单  ...

  10. Python 语法提示vim配置

    1. pydiction 2. 默认 Vim 7.xx以上版本 python_pydiction.vim -- Vim plugin that autocompletes Python code. c ...