nicolas9974

javaweb学习中,QQ476551973,欢迎结交web爱好者

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);
	}
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nicolas9974/article/details/46807567
个人分类: JavaBean
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

JavaBean BeanUtils包操作JavaBean类

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭