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

org.zodiac.fastorm.rdb.utils.PropertiesUtils Maven / Gradle / Ivy

The newest version!
package org.zodiac.fastorm.rdb.utils;

import org.apache.commons.beanutils.BeanUtilsBean;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Deprecated
public abstract class PropertiesUtils {

    private PropertiesUtils() {
        super();
    }

    public static PropertyDescriptor[] getDescriptors(Class clazz) {
        Map nameShorts = new HashMap<>();
        int i = 0;
        Class temp = clazz;
        int obj = 1;
        while (temp != Object.class) {
            for (Field declaredField : temp.getDeclaredFields()) {
                nameShorts.put(declaredField.getName(), i++);
            }
            temp = temp.getSuperclass();
            i = -(obj++ * 1000);
        }
        return Arrays
                .stream(BeanUtilsBean
                                .getInstance()
                                .getPropertyUtils()
                                .getPropertyDescriptors(clazz))
                .sorted(Comparator.comparingInt(p -> nameShorts.getOrDefault(p.getName(), Integer.MAX_VALUE)))
                .toArray(PropertyDescriptor[]::new);
    }

    public static List convertList(Object object) {
        if (object == null) {
            return Collections.emptyList();
        }
        if (object instanceof Object[]) {
            return Arrays.asList(((Object[]) object));
        }
        if (object instanceof Collection) {
            return new ArrayList<>(((Collection) object));
        }

        return Arrays.asList(object);
    }

    public static Optional getPropertyField(Class clazz, String fieldName) {
        Field field = null;
        Class tmp = clazz;
        do {
            try {
                field = tmp.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                tmp = tmp.getSuperclass();
                if (tmp == null || tmp == Object.class) {
                    break;
                }
            }
        } while (field == null);
        return Optional.ofNullable(field);
    }

}