利用BeanUtils与PropertyUtils进行javabean的内省操作

package com.franky.bean;

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

/**
 * @描述 BeanUtils与PropertyUtils的使用	需要JAR包commons-beanutils.jar与commons-logging-1.1.jar
 * @作者 franky
 * @日期 2014-12-31 下午12:04:24
 */
public class JavaBeanTestWithBeanUtils {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		Point point = new Point(5, 5);
		
		//beanutils操作bean的属性都会转换为字符串
		//利用beanutils得到bean对象的属性值
		System.out.println(BeanUtils.getProperty(point, "x"));
		//BeanUtils返回的是String类型
		System.out.println(BeanUtils.getProperty(point, "x").getClass().getName());
		
		//利用beanutils设置bean对象的属性值
		BeanUtils.setProperty(point, "x", 10);
		System.out.println(BeanUtils.getProperty(point, "x"));
		
		//可以对非基本类型的属性进行级联操作,获取date属性中的time
		//将非基本类型的属性对象同样当作bean对象操作
		System.out.println(BeanUtils.getProperty(point, "date.time"));
		//设置date的time属性值,BeanUtils只支持8种基本数据类型的转换,其他类型需要进行ConvertUtils.register();进行类型转换
		BeanUtils.setProperty(point, "date.time", 1234567);
		System.out.println(BeanUtils.getProperty(point, "date.time"));
		
		//利用PropertyUtils进行属性值的获取,返回的值类型为属性的本类型
		//而不是BeanUtils返回的都是String类型
		
		System.out.println(PropertyUtils.getProperty(point, "x"));
		//本类型为Integer
		System.out.println(PropertyUtils.getProperty(point, "x").getClass().getName());
		
	}

}

Point类:

package com.franky.bean;

import java.util.Date;

public class Point {
		private int x;
		private int y;
		private Date date = new Date();
		/**
		 * @return the date
		 */
		public Date getDate() {
			return date;
		}
		/**
		 * @param date the date to set
		 */
		public void setDate(Date date) {
			this.date = date;
		}
		/**
		 * @return the x
		 */
		public int getX() {
			return x;
		}
		/**
		 * @param x the x to set
		 */
		public void setX(int x) {
			this.x = x;
		}
		/**
		 * @return the y
		 */
		public int getY() {
			return y;
		}
		/**
		 * @param y the y to set
		 */
		public void setY(int y) {
			this.y = y;
		}
		public Point(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}
	}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值