Apache Commons Beanutils 一 (使用PropertyUtils访问Bean属性)

简介:

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:

  View Code

调用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:

  View Code

使用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:

  View Code

使用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



本文转自风一样的码农博客园博客,原文链接:http://www.cnblogs.com/chenpi/p/6917499.html,如需转载请自行联系原作者

相关文章
|
6月前
|
Apache
java.lang.NoClassDefFoundError: org/apache/commons/io/output/UnsynchronizedByteArrayOutputStream
java.lang.NoClassDefFoundError: org/apache/commons/io/output/UnsynchronizedByteArrayOutputStream
178 0
|
4天前
|
安全 Linux 网络安全
Linux _ apache服务器部署 不同域名—访问不同网站(多网站)
Linux _ apache服务器部署 不同域名—访问不同网站(多网站)
|
4天前
|
Java Apache Spring
Spring BeanUtils与Apache BeanUtils提供基本属性复制,适用于简单需求
【5月更文挑战第4天】Spring BeanUtils与Apache BeanUtils提供基本属性复制,适用于简单需求;Cglib BeanCopier用于转换为Cglib代理对象;Apache PropertyUtils处理属性操作;Dozer支持复杂对象映射。选择工具取决于具体需求,如需精细控制或对象映射,推荐Dozer或Apache PropertyUtils。Apache BeanUtils可能因潜在的封装性破坏被禁用。
24 3
|
7月前
|
网络安全 API Apache
将Apache服务与内网穿透结合,让您的网站可以公网访问
将Apache服务与内网穿透结合,让您的网站可以公网访问
|
4天前
|
算法 Java Apache
Apache Commons
Apache Commons是一个开源项目,提供了一系列的工具和库,用于简化Java开发中的常见任务。
26 1
|
4天前
|
API Windows
解决echarts.apache.org官网不能访问的问题(主要是用于查看配置项API参数细节说明)
解决echarts.apache.org官网不能访问的问题(主要是用于查看配置项API参数细节说明)
|
5月前
|
Java Apache Spring
Spring BeanUtils 2、Cglib BeanCopier 3、Apache BeanUtils 4、Apache PropertyUtils 5、Dozer 那么,我们到底应该选择哪种工具类更加合适呢?为什么Java开发手册中提到禁止使用Apache BeanUtils呢
Spring BeanUtils 2、Cglib BeanCopier 3、Apache BeanUtils 4、Apache PropertyUtils 5、Dozer 那么,我们到底应该选择哪种工具类更加合适呢?为什么Java开发手册中提到禁止使用Apache BeanUtils呢
61 0
|
7月前
|
Apache
记一次apache访问问题
记一次apache访问问题
|
8月前
|
SQL 安全 数据可视化
Apache Superset 未授权访问漏洞(CVE-2023-27524)
Apache Superset 存在未授权访问漏洞,攻击者可利用该漏洞验证和访问未经授权的资源。
148 1
|
12月前
|
移动开发 前端开发 Java
Spring MVC-09循序渐进之文件上传(基于Apache Commons FileUpload)
Spring MVC-09循序渐进之文件上传(基于Apache Commons FileUpload)
77 0

热门文章

最新文章

推荐镜像

更多