diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/Enumeration.java b/src/main/java/xyz/zhouxy/plusone/commons/util/Enumeration.java index 8c255a2..c24663c 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/util/Enumeration.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/Enumeration.java @@ -17,11 +17,13 @@ package xyz.zhouxy.plusone.commons.util; import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; import java.util.Objects; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; + +import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod; + /** * 枚举类 */ @@ -30,8 +32,9 @@ public abstract class Enumeration> implements Comparabl protected final String name; protected Enumeration(final int id, final String name) { + Assert.hasText(name, "Name of enumeration must has text."); this.id = id; - this.name = Objects.requireNonNull(name); + this.name = name; } public final int getId() { @@ -70,16 +73,20 @@ public abstract class Enumeration> implements Comparabl } protected static final class ValueSet> { - private final Map valueMap; + private final ImmutableMap valueMap; + + private ValueSet(ImmutableMap valueMap) { + this.valueMap = valueMap; + } @SafeVarargs - public ValueSet(T... values) { - Map temp = new HashMap<>(values.length); + @StaticFactoryMethod(ValueSet.class) + public static > ValueSet of(T... values) { + Builder builder = ImmutableMap.builder(); for (T value : values) { - Assert.notNull(value, "Value must not be null."); - temp.put(value.getId(), value); + builder.put(value.getId(), value); } - this.valueMap = Collections.unmodifiableMap(temp); + return new ValueSet<>(builder.build()); } public T get(int id) { diff --git a/src/test/java/xyz/zhouxy/plusone/commons/EnumerationTests.java b/src/test/java/xyz/zhouxy/plusone/commons/EnumerationTests.java index 983906c..b1d5154 100644 --- a/src/test/java/xyz/zhouxy/plusone/commons/EnumerationTests.java +++ b/src/test/java/xyz/zhouxy/plusone/commons/EnumerationTests.java @@ -38,8 +38,7 @@ final class EntityStatus extends Enumeration { public static final EntityStatus AVAILABLE = new EntityStatus(0, "正常"); public static final EntityStatus DISABLED = new EntityStatus(1, "禁用"); - private static final ValueSet VALUE_SET = new ValueSet<>( - AVAILABLE, DISABLED); + private static final ValueSet VALUE_SET = ValueSet.of(AVAILABLE, DISABLED); public static EntityStatus of(int value) { return VALUE_SET.get(value); @@ -58,7 +57,7 @@ final class Result extends Enumeration { public static final Result SUCCESSFUL = new Result(1, "成功"); public static final Result FAILURE = new Result(0, "失败"); - private static final ValueSet VALUE_SET = new ValueSet<>(SUCCESSFUL, FAILURE); + private static final ValueSet VALUE_SET = ValueSet.of(SUCCESSFUL, FAILURE); public static Result of(int id) { return VALUE_SET.get(id);