2011年5月30日星期一

  Groovy将字符串类型转换为自定义类型的方法

将一个字符串转换为自定义类型:

例如Quantity是自定义的一个class,现在想这么调用
Quantity quantity = "100个" as Quantity

def quantity = "100个".asType(Quantity)

需要重载String的asType方法(String.metaClass.asType)。具体实现如下(注意static方法块):


package com.cninsure.datatype

/**
* 数量单位
*/
class Quantity extends InsDataType {
    Number amount
    String unit

    Quantity() {
    }

    static {
        String.metaClass.asType {  Class c ->
            if (Quantity == c) {
                Quantity.from(delegate)
            } else {
                delegate.asType(c)
            }
        }
    }

    @Override
    void build(val) {
        if (val instanceof Quantity) {
            this.amount = val.amount
            this.unit = val.unit
            return
        }
        def regular = /^(\d+(\.\d+)?)\s?(\S+)?/
        if (!(val ==~ regular)) {
            throw new IllegalArgumentException("模式不匹配")
        }
        def result = (val =~ regular)           //拆分
        Number value = result[0][1]
        String qu = result[0][3]

        this.amount = value
        this.unit = qu
        return
    }

    static Quantity from(val) {
        if (val instanceof Quantity) return val
        Quantity quantity = new Quantity()
        quantity.build(val)
        return quantity
    }

    @Override
    boolean identity(Object val) {
        if (!(val instanceof Quantity)) {
            val = from(val)
        }
        if (amount == val.amount && unit == val.unit) return true
        return false
    }

    @Override
    String display() {
        return amount.toString() + unit.toString()
    }


    public String toString() {
        return "Quantity{" +
                "amount=" + amount +
                ", unit='" + unit + '\'' +
                '}';
    }
}

没有评论:

发表评论