castor Date date-format

TODO

 

package mytest.utils.castor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.exolab.castor.mapping.ConfigurableFieldHandler;
import org.exolab.castor.mapping.GeneralizedFieldHandler;
import org.exolab.castor.mapping.ValidityException;

public class DateFieldHandlerImpl extends GeneralizedFieldHandler implements ConfigurableFieldHandler {

	private SimpleDateFormat formatter;

	public void setConfiguration(Properties config) throws ValidityException {
		String pattern = config.getProperty("date-format");
		if (pattern == null) {
			throw new ValidityException("Required parameter \"date-format\" is missing for FieldHandlerImpl.");
		}
		try {
			formatter = new SimpleDateFormat(pattern);
		} catch (IllegalArgumentException e) {
			throw new ValidityException("Pattern \"" + pattern + "\" is not a valid date format.");
		}
	}

	@Override
	public Object convertUponGet(Object value) {
		if (value == null)
			return null;
		
		Date date = (Date) value;
		return formatter.format(date);
	}

	@Override
	public Object convertUponSet(Object value) {

		Date date = null;
		try {
			date = formatter.parse((String) value);
		} catch (ParseException px) {
			throw new IllegalArgumentException(px.getMessage());
		}
		
		return date;
	}

	@Override
	public Class getFieldType() {

		return Date.class;
	}

}

 

import java.util.Date;

public class TestBean {
	
	private Date d1;
	private Date d2;
	
	//setter and gettter
	
}

 

<?xml version="1.0"?>
<mapping>

	<field-handler name="handler1" class="mytest.utils.castor.DateFieldHandlerImpl">
		<param name="date-format" value="yyyyMMdd" />
	</field-handler>

	<field-handler name="handler2" class="mytest.utils.castor.DateFieldHandlerImpl">
		<param name="date-format" value="yyyyMMddHHmmss" />
	</field-handler>

	<class name="mytest.TestBean">

		<field name="d1" type="string" handler="handler1">
			<bind-xml name="D1" node="element" />
		</field>

		<field name="d2" type="string" handler="handler2">
			<bind-xml name="D2" node="element" />
		</field>

	</class>

</mapping>

注意: field-handler不能共享 

在多线程下使用DateFieldHandlerImpl,formatter好像有问题,放到方法中

 

 参考http://castor.codehaus.org/xml-fieldhandlers.html

你可能感兴趣的:(format)