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

com.fastchar.utils.FastEnumUtils Maven / Gradle / Ivy

package com.fastchar.utils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("unchecked")
public class FastEnumUtils {


    public static  T formatToEnum(Class clazz, int index){
        return formatToEnum(clazz, index, null);
    }

    public static  T formatToEnum(Class clazz, int index, Enum defaultValue) {
        try {
            Enum[] c = clazz.getEnumConstants();
            if (index >= c.length) {
                return (T) defaultValue;
            }
            return (T) c[index];
        } catch (Exception ignored) {
        }
        return (T) defaultValue;
    }


    public static  T formatToEnum(Class clazz, String name){
        return formatToEnum(clazz, name, null);
    }

    public static  T formatToEnum(Class clazz, String name, Enum defaultValue) {
        try {
            if (name == null) {
                return (T) defaultValue;
            }
            int index = FastNumberUtils.formatToInt(name, -1);
            if (index >= 0) {
                return formatToEnum(clazz, index, defaultValue);
            }
            return (T) Enum.valueOf(clazz, name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) defaultValue;
    }

    public static  T[] getEnumValues(Class targetClass) {
        return targetClass.getEnumConstants();
    }

    public static  T[] getEnumValues(Class targetClass, String... keys) {
        List enumList = new ArrayList<>();
        T[] enumConstants = targetClass.getEnumConstants();
        for (T enumConstant : enumConstants) {
            for (String key : keys) {
                if (enumConstant.name().contains(key)) {
                    enumList.add(enumConstant);
                    break;
                }
            }
        }
        return enumList.toArray((T[]) Array.newInstance(targetClass, enumList.size()));
    }

    public static Integer[] getEnumOrdinals(Class targetClass, String... keys) {
        List enumList = new ArrayList<>();
        Enum[] enumConstants = targetClass.getEnumConstants();
        for (Enum enumConstant : enumConstants) {
            for (String key : keys) {
                if (enumConstant.name().contains(key)) {
                    enumList.add(enumConstant.ordinal());
                    break;
                }
            }
        }
        return enumList.toArray(new Integer[]{});
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy