All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.lulihu.ObjectKit.PropertiesKit Maven / Gradle / Ivy

package net.lulihu.ObjectKit;


import net.lulihu.ObjectKit.annotation.Prop;

import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Properties 对象工具类
 */
public class PropertiesKit {

    private PropertiesKit() {
    }

    /**
     * bean转 Properties对象
     *
     * @param bean 需要转换的对象
     */
    public static  Properties beanToProperties(T bean) throws IllegalAccessException {
        Objects.requireNonNull(bean);

        Properties result = new Properties();
        List fields = ReflectKit.getAllFieldsList(bean.getClass());

        String name = null;
        try {
            for (Field field : fields) {
                Prop prop = field.getAnnotation(Prop.class);
                if (prop == null) continue;

                name = field.getName();
                Object value = ReflectKit.getFieldValue(bean, name);

                result.put(prop.value(), value);
            }
        } catch (IllegalAccessException e) {
            throw new IllegalAccessException(StrKit.format("非法访问属性[{}]例外", name));
        }
        return result;
    }

    private static final Map propertiesMap = new ConcurrentHashMap<>();

    /**
     * 获取默认配置
     */
    public static ConfigProperties getDefaultProperties() {
        return getConfigProperties("config.properties");
    }

    /**
     * 自定义文件解析 **.property
     *
     * @param file 配置文件
     */
    public static ConfigProperties getConfigProperties(File file) {
        return propertiesMap.computeIfAbsent(file.getPath(), k -> new ConfigProperties(file));
    }

    /**
     * 自定义文件解析**.property
     * 

* 注意该方法只解析jar包内的文件地址 * * @param configFile 配置文件地址 */ public static ConfigProperties getConfigProperties(String configFile) { return propertiesMap.computeIfAbsent(configFile, ConfigProperties::new); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy