初用org.apache.commons.beanutils.Convert

王朝java/jsp·作者佚名  2006-01-31
窄屏简体版  字體: |||超大  

org.apache.commons.beanutils.ConvertUtils

这是一个接口,其中只包含一个方法convert(java.lang.Class type, java.lang.Object value),其功能是将输入参数value转换为指定类型type的实例。

范例:

我建立了一个Rectangle对象,并为这rectangle对象建立了一个RectangleConverter,随后将RectangleConverter注册进ConvertUtils中。形为{3,2}的字符串可以转变为一个rectangle。

这里唯一要说明的就是RectangleConverter中要实现两个converter方法,也就是要对接口Converter中定义的方法进行overload,从而可以实现字符串和Rectangle之间的互相转换了。

代码如下:

package beanutil;

import java.util.StringTokenizer;

import org.apache.commons.beanutils.ConvertUtils;

import org.apache.commons.beanutils.Converter;

/**

* @author samepoint

*

*/

public class RectangleConverter implements Converter {

public Object convert(Class arg0, Object arg1) {

if (arg1 instanceof String)

return convert(arg0, arg1.toString());

return convert(arg0, (Rectangle) arg1);

}

/**

* convert a string to a instance of rectangle

* @param rectangleType

* @param para

* @return

*/

public Rectangle convert(Class rectangleType, String para) {

StringTokenizer token = new StringTokenizer(para, ",");

Double temp1, temp2 = null;

temp1 = (Double) ConvertUtils.convert(token.nextToken(), Double.class);

temp2 = (Double) ConvertUtils.convert(token.nextToken(), Double.class);

Rectangle rect = new Rectangle();

rect.setLength(Math.max(temp1.doubleValue(), temp2.doubleValue()));

rect.setWidth(Math.min(temp1.doubleValue(), temp2.doubleValue()));

return rect;

}

/**

* convert a instance of rectangle to string

* @param string

* @param rect

* @return

*/

public String convert(Class string, Rectangle rect) {

StringBuffer buffer = new StringBuffer("(");

buffer.append(rect.getLength()).append(",");

buffer.append(rect.getWidth());

return buffer.toString();

}

}

将RectangleConverter注册到ConvertUtils中,我们就可以把形为{4,5}的字符串转换为Rectangle的实例,同样可以将Rectangle的实例转换为形为{4,5}的字符串。

另附Rectangle的代码:

/*

* Created on 2005-7-5

*/

package beanutil;

/**

* @author samepoint

*/

public class Rectangle {

double length = 0.0d;

double width = 0.0d;

/**

* @return Returns the length.

*/

public double getLength() {

return length;

}

/**

* @param length The length to set.

*/

public void setLength(double length) {

this.length = length;

}

/**

* @return Returns the width.

*/

public double getWidth() {

return width;

}

/**

* @param width The width to set.

*/

public void setWidth(double width) {

this.width = width;

}

public double computeArea(){

return length*width;

}

public String toString(){

StringBuffer buffer = new StringBuffer("(");

buffer.append(getLength()).append(",");

buffer.append(getWidth()).append(")");

return buffer.toString();

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航