「Struts2開発」BeanUtilsクラスの使い方

Javaコード:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.junit.Test;
import org.changfapjPerson;

public class SampleInfo {

// 属性設定
@Test
public void sampleFunc1() throws Exception {
Person p = new Person();
BeanUtils.setProperty(p, “name", “yamada");
BeanUtils.setProperty(p, “age", 30);
System.out.println(p.getName());
System.out.println(p.getAge());
}

// registerの定義
@Test
public void sampleFunc2() throws Exception {
Person p = new Person();
ConvertUtils.register(new Converter() {

@Override
public Object convert(Class type, Object value) {
if (value == null) {
return null;
}
if (!(value instanceof String)) {
throw new ConversionException(“conversion error");
}
String str = (String) value;
if (str.trim().equals(“")) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd");
try {
return sdf.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);
}

}

}, Date.class);
BeanUtils.setProperty(p, “birth", “1987-10-10");
System.out.println(p.getBirth().toLocaleString());
}

@Test
public void sampleFunc3() throws Exception {
Person p = new Person();
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.setProperty(p, “birth", “1986-10-10");
System.out.println(p.getBirth().toLocaleString());
}

@Test
public void sampleFunc4() throws Exception {
Map dp = new HashMap();
dp.put(“name", “yamada");
dp.put(“age", “30");
dp.put(“birth", “1987-10-10");
ConvertUtils.register(new DateLocaleConverter(), Date.class);
Person p = new Person();
BeanUtils.populate(p, dp);
System.out.println(p.getAge());
System.out.println(p.getBirth());
}
}

Java

Posted by arkgame