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

cn.handyplus.lib.core.BeanUtil Maven / Gradle / Ivy

The newest version!
package cn.handyplus.lib.core;

import cn.handyplus.lib.constants.BaseConstants;
import org.bukkit.Bukkit;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Map;
import java.util.logging.Level;

/**
 * bean工具
 *
 * @author handy
 * @since 1.4.8
 */
public class BeanUtil {

    private BeanUtil() {
    }

    /**
     * bean转map
     *
     * @param obj 对象
     * @return map
     */
    public static Map beanToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        Map map = MapUtil.of();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性
                if (!BaseConstants.CLASS.equals(key)) {
                    map.put(key, property.getReadMethod().invoke(obj));
                }
            }
        } catch (Exception e) {
            Bukkit.getLogger().log(Level.SEVERE, "beanToMap 发生异常", e);
        }
        return map;
    }

    /**
     * map转bean
     *
     * @param clazz beanType
     * @param map   map
     * @param    类型
     * @return bean
     * @since 3.1.6
     */
    public static  T mapToBean(Class clazz, Map map) {
        T obj = null;
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            obj = clazz.getDeclaredConstructor().newInstance();
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                String propertyName = descriptor.getName();
                if (map.containsKey(propertyName)) {
                    descriptor.getWriteMethod().invoke(obj, map.get(propertyName));
                }
            }
        } catch (Exception e) {
            Bukkit.getLogger().log(Level.SEVERE, "mapToBean 发生异常", e);
        }
        return obj;
    }

    /**
     * 生成bean
     *
     * @param clazz beanType
     * @param    类型
     * @return bean
     * @since 3.2.8
     */
    public static  T createBean(Class clazz) {
        T obj = null;
        try {
            obj = clazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            Bukkit.getLogger().log(Level.SEVERE, "createBean 发生异常", e);
        }
        return obj;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy