PropertyUtils的使用
生活随笔
收集整理的這篇文章主要介紹了
PropertyUtils的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言:本博客內容由張孝祥Java高新技術整理而來
在上節:對javaBean簡單的內省操作?中我們寫了兩個靜態的方法,用來獲取和賦值javaBean屬性。其實這些apache早已經幫我們封裝好了,我們直接使用即可。
準備工作:兩個jar包
1.commons-beanutils.jar
2.commons-logging.jar
直接上實例
po實體類
vo實體類
測試類
package com.dao.chu.movie;import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map;import org.apache.commons.beanutils.PropertyUtils;public class PropertyUtilTest {@SuppressWarnings("unchecked") public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, NoSuchMethodException {Student student = new Student(1, "張三", 18);StudentVo studentVo = new StudentVo();//設置屬性 同方法 BeanUtils.setPropertyPropertyUtils.setProperty(student, "name", "張三三");//獲取屬性 同方法 BeanUtils.getPropertyObject name = PropertyUtils.getProperty(student, "name");System.out.println("getName is:"+name);//vo po轉換System.out.println(studentVo);PropertyUtils.copyProperties(studentVo, student);System.out.println("vo is:"+studentVo);//po轉換為map 同BeanUtils.describeMap<String, Object> map = new HashMap<String, Object>();map=PropertyUtils.describe(studentVo);System.out.println("map is:"+map.toString());//map賦值 PropertyUtils.setProperty(map, "father", "張五五");System.out.println("now map is:"+map.toString());} }運行結果:
getName is:張三三
StudentVo [id=0, name=null, age=0, grade=0.0]
vo is:StudentVo [id=1, name=張三三, age=18, grade=0.0]
map is:{grade=0.0, name=張三三, id=1, class=class com.dao.chu.movie.StudentVo, age=18}
now map is:{grade=0.0, father=張五五, name=張三三, id=1, class=class com.dao.chu.movie.StudentVo, age=18}
總結
以上是生活随笔為你收集整理的PropertyUtils的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL Server 2008 R2安装
- 下一篇: [数论] 小球碰撞