JavaBean BeanUtils包操作JavaBean类

Point类(要操作的JavaBean类)

package test;

public class Point {
	private double x;
	private double y;

	public double getX() {
		return x;
	}

	public void setX(double x) {
		this.x = x;
	}

	public double getY() {
		return y;
	}

	public void setY(double y) {
		this.y = y;
	}

	/**
	 * @param x
	 * @param y
	 */
	public Point(double x, double y) {
		super();
		this.x = x;
		this.y = y;
	}

	@Override
	public String toString() {
		return "Point [x=" + x + ", y=" + y + "]";
	}
}

BeanUtils包操作JavaBean类

package test;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.BeanUtils;

public class MainTest {
	public static void main(String[] args) throws IllegalArgumentException,
			IntrospectionException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {

		Point p = new Point(3, 5);
		System.out.println("变量:  " + p);

		System.out.println("p.getX() = : " + BeanUtils.getProperty(p, "x"));
		System.out.println("");

		System.out.println("第三个参数的变量类型是 double(Point类中x的变量类型)");
		BeanUtils.setProperty(p, "x", 12);
		System.out.println(p);
		System.out.println("");

		System.out.println("第三个参数的变量类型是 String(setProperty内部自动会转化成相应的变量的类型)");
		BeanUtils.setProperty(p, "x", "13");
		System.out.println(p);
		System.out.println("");

		Map<String, String> map = BeanUtils.describe(p);
		System.out.println("describe方法调用获取map");
		for (Entry<String, String> it : map.entrySet()) {
			System.out.println(it.getKey() + "=" + it.getValue());
		}
		System.out.println("");
		
		System.out.println("populate方法, 通过map变量赋值给JavaBean类");
		HashMap<String, Double> set = new HashMap<String, Double>();
		set.put("x", 1000.0);
		set.put("y", 2000.0);
		BeanUtils.populate(p, set);
		System.out.println(p);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值