您的位置:首页 > 编程语言 > Java开发

使用beanUtils操纵javabean

2013-05-22 09:48 239 查看
package com.lan.beanutils;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.junit.Test;

import sun.java2d.pipe.SpanShapeRenderer.Simple;

//使用beanUtils操作bean的属性
public class Demo {

@Test
public void test1() throws IllegalAccessException, InvocationTargetException{

Person person = new Person();

BeanUtils.setProperty(person, "name", "xxxx");

System.out.println(person.getName());
}

@Test
public void test2() throws IllegalAccessException, InvocationTargetException{

String nameString = "aaa";
String passwordString = "123";
String age = "33";
String birthdayString = "1988-01-01";

Person person = new Person();
BeanUtils.setProperty(person, "name", nameString);
BeanUtils.setProperty(person, "password", passwordString);
BeanUtils.setProperty(person, "age", age);//只支持8种基本数据类型自动转换
//BeanUtils.setProperty(person, "birthday", birthdayString);

System.out.println(person.getName());
System.out.println(person.getPassword());
System.out.println(person.getAge());
//System.out.println(person.getBirthday());

//为了让日期赋到bean的birthday属性上,我们给beanUtils注册一个日期转换器
ConvertUtils.register(new Converter() {

@Override
public Object convert(Class type, Object value) {

if (value == null) {
return null;
}

if (!(value instanceof String)) {
throw new ConversionException("只支持String类型的转换!");
}

String str = (String)value;

if (str.trim().equals("")) {
return null;
}

SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);//异常链不能断
}
}
}, Date.class);

BeanUtils.setProperty(person, "birthday", birthdayString);
System.out.println(person.getBirthday());

Date date = person.getBirthday();
System.out.println(date.toLocaleString());
}
}


package com.lan.beanutils;

import java.util.Date;

//javabean
public class Person {

private String name;
private String password;
private int age;
private Date birthday;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: