工作中经常会遇到将行数据转换成Java(POJO)对象的场景,其中关于字段校验和类型转换的处理繁琐而冗余,对于有代码洁癖的人着实不能忍。这里分享下自己封装的工具代码,也许能够帮助你更简单地完成此类任务。

 

先将以下五个文件加入你豪华午餐(项目????)中

FieldItem:

/**
 * 
 * @author lichmama
 *
 */
public class FieldItem {

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public FieldProcessor getProcessor() {
        return processor;
    }

    public void setProcessor(FieldProcessor processor) {
        this.processor = processor;
    }

    public void setValidator(FieldValidator validator) {
        this.validator = validator;
    }

    public FieldValidator getValidator() {
        return validator;
    }

    public boolean validate() {
        return validator.validate(this);
    }

    public Object process() throws Exception {
        return processor.process(this);
    }

    private int index;

    private String name;

    private Object value;

    private FieldValidator validator = new FieldValidator() {

        @Override
        public boolean validate(FieldItem field) {
            return true;
        }

    };

    private FieldProcessor processor = new FieldProcessor() {

        @Override
        public Object process(FieldItem field) {
            return field.getValue();
        }

    };

    public FieldItem() {

    }

    public FieldItem(int index, String name) {
        this.index = index;
        this.name = name;
    }

    public FieldItem(int index, String name, FieldValidator validator) {
        this.index = index;
        this.name = name;
        this.validator = validator;
    }

    public FieldItem(int index, String name, FieldProcessor processor) {
        this.index = index;
        this.name = name;
        this.processor = processor;
    }

    public FieldItem(int index, String name, FieldValidator validator, FieldProcessor processor) {
        this.index = index;
        this.name = name;
        this.validator = validator;
        this.processor = processor;
    }
}
View Code

相关文章: