将行数据转换成Java(POJO)对象

Posted lichmama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将行数据转换成Java(POJO)对象相关的知识,希望对你有一定的参考价值。

工作中经常会遇到将行数据转换成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

 

FieldProcessor:

技术图片
/**
 * 扩展接口:可针对字段做个性化处理
 * 
 * @author lichmama
 *
 */
public interface FieldProcessor 

    Object process(FieldItem field) throws Exception;
View Code

 

FieldValidator:

技术图片
/**
 * 校验接口:可针对字段做个性化校验
 * 
 * @author lichmama
 *
 */
public interface FieldValidator 

    boolean validate(FieldItem field);
View Code

 

ConvertException:

技术图片
/**
 * 转换异常
 * 
 * @author lichmama
 *
 */
public class ConvertException extends RuntimeException 

    public ConvertException(String msg) 
        super(msg);
    

    public ConvertException(Throwable throwable) 
        super(throwable);
    

    public ConvertException(String msg, Throwable throwable) 
        super(msg, throwable);
    
View Code

 

RowConverter:

技术图片
/**
 * 行转换器:用于将行数据转换成bean
 * 
 * @author lichmama
 *
 */
public class RowConverter 

    private Map<String, FieldItem> fieldMap = new HashMap<String, FieldItem>();

    public RowConverter() 

    public RowConverter(String[] fieldNames) 
        for (int i = 0; i < fieldNames.length; i++) 
            String name = fieldNames[i];
            FieldItem field = new FieldItem();
            field.setIndex(i);
            field.setName(name);
            fieldMap.put(name, field);
        
    

    public void setField(FieldItem field) 
        if (field == null) 
            throw new ConvertException("field is null");
        
        String name = field.getName();
        if (!fieldMap.containsKey(name))   
            throw new ConvertException("the field \"" + name + "\" not found");
        
        fieldMap.put(name, field);
    

    public void setFieldValidator(String name, FieldValidator validator) 
        if (!fieldMap.containsKey(name)) 
            throw new ConvertException("the field \"" + name + "\" not found");
        
        fieldMap.get(name).setValidator(validator);
    

    public void setFieldProcessor(String name, FieldProcessor processor) 
        if (!fieldMap.containsKey(name)) 
            throw new ConvertException("the field \"" + name + "\" not found");
        
        fieldMap.get(name).setProcessor(processor);
    

    public <T> T convert(Object[] row, Class<T> beanClass) throws Exception 
        Map<String, Object> properties = new HashMap<String, Object>();
        Iterator<FieldItem> iter = fieldMap.values().iterator();
        while (iter.hasNext()) 
            FieldItem field = iter.next();
            Object value = row[field.getIndex()];
            field.setValue(value);
            if (!field.validate()) 
                throw new ConvertException("the field \"" + field.getName() + "\" validate failed");
            
            Object processedValue = field.process();
            properties.put(field.getName(), processedValue);
        
        T bean = beanClass.newInstance();
        // powered by commons-beanutils
        BeanUtils.populate(bean, properties);
        return bean;
    
    
View Code

 

下面我们就可以愉快的写代码了:

目标类User:

public class User implements Serializable 

    private int id;
    
    private String name;
    
    private String gender;
    
    private int age;
    
    private String birthday;
    
    // 省略getter、setter

    @Override
    public String toString() 
        return "User [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + ", birthday=" + birthday
                + "]";
    

 

测试类Test:

public class Test 

    public static void main(String[] args) throws Exception 
        String[] fieldNames =  "id", "name", "gender", "age", "birthday" ;
        Object[] row =  1, "lichmama", "man", 17, new Date() ;
        RowConverter converter = new RowConverter(fieldNames);

        testValidator(row, converter);
        testProcessor(row, converter);
    

    /**
     * 字段个性化校验
     * 
     * @param row
     * @param converter
     * @throws Exception
     */
    public static void testValidator(Object[] row, RowConverter converter) throws Exception 
        converter.setFieldValidator("age", (FieldItem field) -> 
            int age = (int) field.getValue();
            return age >= 18; // 未成年禁止入内??
        );

        User user = converter.convert(row, User.class);
    

    /**
     * 字段个性化处理
     * 
     * @param row
     * @param converter
     * @throws Exception
     */
    public static void testProcessor(Object[] row, RowConverter converter) throws Exception 
        converter.setFieldProcessor("birthday", (FieldItem field) -> 
            return new SimpleDateFormat("yyyy-MM-dd").format(field.getValue()); // 将日期转换成格式化字符串
        );

        User user = converter.convert(row, User.class);
    

 

看上去是不是好多了??

以上是关于将行数据转换成Java(POJO)对象的主要内容,如果未能解决你的问题,请参考以下文章

Jpa 从POJO 转换成表

在 Java 中将 POJO 转换为表单数据

使用json-org包实现POJO和json的转换

怎么将BigDecimal转换成Int

SparkSQL + Java:使用数据集时将 Pojo 转换为表格格式

使用jackson将pojo(对象列表)转换为java中的json