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

io.github.firefang.power.common.util.EnumUtil Maven / Gradle / Ivy

There is a newer version: 0.0.6
Show newest version
package io.github.firefang.power.common.util;

import java.util.Optional;
import java.util.function.BiPredicate;

/**
 * 枚举工具类
 * 
 * @author xinufo
 *
 */
public abstract class EnumUtil {
    private static final BiPredicate, String> STRICT = (e, n) -> {
        return e.name().equals(n);
    };
    private static final BiPredicate, String> NOT_STRICT = (e, n) -> {
        return e.name().equalsIgnoreCase(n);
    };

    public static > T fromString(Class enumType, String name) {
        return fromString(enumType, name, false);
    }

    @SuppressWarnings("unchecked")
    public static > T fromString(Class enumType, String name, boolean strict) {
        BiPredicate p;
        if (strict) {
            p = (BiPredicate) STRICT;
        } else {
            p = (BiPredicate) NOT_STRICT;
        }
        for (T e : enumType.getEnumConstants()) {
            if (p.test(e, name)) {
                return e;
            }
        }
        return null;
    }

    public static > Optional fromStringOptional(Class enumType, String name) {
        return Optional.ofNullable(fromString(enumType, name, false));
    }

    public static > Optional fromStringOptional(Class enumType, String name, boolean strict) {
        return Optional.ofNullable(fromString(enumType, name, strict));
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy