BeanUtils的简单使用

阅读更多

BeanUtils的简单使用

1、导入相应的Jar包

commons-beanutils-1.8.3.jar
commons-logging-1.1.2.jar

2、用于测试的Test类(JavaBean)

package reflect;

import java.util.Date;

public class Test {

	private Integer x;
	// 此处必须要实例化,不然后面测试对象为空
	private Date date = new Date();

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public Test(Integer x) {
		super();
		this.x = x;
	}

	public Integer getX() {
		return x;
	}

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

 3、测试用TestBeanUtils

package reflect;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;

public class TestBeanUtils {

	public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		
		Test t = new Test(4);
		
		System.out.println(BeanUtils.getProperty(t, "x"));
		System.out.println(BeanUtils.getProperty(t, "x").getClass().getName());
		
		BeanUtils.setProperty(t, "x", 10);
		System.out.println(BeanUtils.getProperty(t, "x"));
		
		// 此处所使用的date必须已经实例化了
		BeanUtils.setProperty(t, "date.time", 555);
		System.out.println(BeanUtils.getProperty(t, "date.time"));
	}
}

 4、运行结果

4
java.lang.String
10
555

 其余方法,可自行实验,没有什么难度……

 

你可能感兴趣的:(BeanUtils的简单使用)