property文件到vo对象的映射工具类

  • 在java开发中经常要用到配置文件,经常需要读取和保存配置文件,特别是读取配置文件。但是配置文件默认是String类型的,而配置文件中经常会出现int,long,boolean,double,float等,这就使得我们必须进行类型的转换,在类型转换的过程中常常会出错,所以就开发了这个工具类。
  • 优点
    • 能够把配置文件映射为一个对象,对象还可定义默认值。
    • 采用反射,打印属性比较简洁
    • 减少字符串到具体类型之间的转换时发生的错误

工具类定义

package property;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * VO 对象限制:
 * 1. vo必须提供默认的无参数构造函数
 * 2. vo必须提供set方法,set方法符合javaBean命名
 * 3. vo的成员变量必须和配置文件的key一致
 */
public class Property2Object {

    private static Object propertyVO;

    //从配置文件的绝对路径获取配置
    public static Object properties2Object(final String filePath, final Class<?> clazz)
            throws FileNotFoundException {
        return properties2Object(new FileInputStream(filePath), clazz);
    }

    //通过文件输入流获取配置
    public static Object properties2Object(final FileInputStream fileInputStream, final Class<?> clazz) {
        Properties properties = new Properties();
        InputStream in = new BufferedInputStream(fileInputStream);
        try {
            properties.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
       return properties2Object(properties, clazz);
    }

    //通过Property
    public static Object properties2Object(final Properties properties, final Class<?> clazz) {

        try {
            //创建vo对象
            propertyVO = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException ex) {
            ex.printStackTrace();
        }

        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("set")) {
                String key = name.substring(3, 4).toLowerCase() + name.substring(4);
                String property = properties.getProperty(key);
                //未设置属性采用vo中的默认值,否则采用新值
                if (property != null) {
                    Class<?>[] parameterType = method.getParameterTypes();
                    String simpleName = parameterType[0].getSimpleName();
                    Object propertyValue = null;
                    if (simpleName.equalsIgnoreCase("String")) {
                        propertyValue = property;
                    } else if (simpleName.equalsIgnoreCase("int")) {
                        propertyValue = Integer.parseInt(property);
                    } else if (simpleName.equalsIgnoreCase("double")) {
                        propertyValue = Double.parseDouble(property);
                    } else if (simpleName.equalsIgnoreCase("long")) {
                        propertyValue = Long.parseLong(property);
                    } else if (simpleName.equalsIgnoreCase("float")) {
                        propertyValue = Float.parseFloat(property);
                    } else if (simpleName.equalsIgnoreCase("boolean")) {
                        propertyValue = Boolean.parseBoolean(property);
                    }

                    try {
                        //调用set方法设置属性为配置文件中的值
                        method.invoke(propertyVO, new Object[]{propertyValue});
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        return propertyVO;
    }

    //通过反射打印对象内容,适用于字段很多的情况
    public static void printObject(Object object) {

        Field[] fields = object.getClass().getDeclaredFields();
        for (Field filed : fields) {
            try {
                filed.setAccessible(true);
                System.out.println(filed.getName() + " : " + filed.get(object));
                filed.setAccessible(false);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}

vo对象

package property;

public class Stu {
    //变量名必须与配置文件中相同,可以设置默认值
    private String name;
    private int age;
    private boolean isMan = false;

    //默认构造函数必须存在
    public Stu() {}

    public Stu(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //必须有set方法,符合JavaBean规范
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean getIsMan() {
        return isMan;
    }

    public void setIsMan(boolean man) {
        isMan = man;
    }
}

配置文件内容

name = jieniyimiao
age = 100
isMan = true

测试类

package property;

import java.io.FileNotFoundException;

public class Test {

    public static void main(String[] args) throws FileNotFoundException {
        Stu stu1 = (Stu) Property2Object.properties2Object(
                "C:\\Users\\jieniyimiao\\Desktop\\idea\\src\\stu.property", Stu.class);
        Property2Object.printObject(stu1);
    }

}

测试结果

name : jieniyimiao
age : 100
isMan : true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值