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

cn.maarlakes.enumx.EnumValue Maven / Gradle / Ivy

Go to download

enumx 提供枚举值的统一接口,枚举值扩展接口,以及一些常见的枚举工具方法。

The newest version!
package cn.maarlakes.enumx;

import jakarta.annotation.Nonnull;

import java.util.Objects;

/**
 * @author linjpxc
 */
public interface EnumValue, T> extends Valuable {

    @Nonnull
    Class getDeclaringClass();

    @Nonnull
    static  & EnumValue, T> E valueOf(@Nonnull Class enumType, @Nonnull T value) {
        Objects.requireNonNull(value, "Value is null");
        final E[] values = enumType.getEnumConstants();
        for (E item : values) {
            if (Objects.equals(item.value(), value)) {
                return item;
            }
        }
        throw new IllegalArgumentException("No enum constant " + enumType.getCanonicalName() + " value: " + value);
    }

    @Nonnull
    static  & EnumValue, V> String toString(@Nonnull E e) {
        final V value = e.value();
        if (value instanceof CharSequence) {
            return value.toString();
        }

        return String.format("%s: %s", e.name(), value);
    }

    @SuppressWarnings("unchecked")
    static  & EnumValue, V> int compare(E left, E right) {
        if (left == right) {
            return 0;
        }
        if (left == null) {
            return -1;
        }
        if (right == null) {
            return 1;
        }

        final Class type = left.valueType();
        if (Comparable.class.isAssignableFrom(type)) {
            final Comparable comparable = (Comparable) left.value();
            return comparable.compareTo(right.value());
        }

        return left.compareTo(right);
    }
}