Java 枚举查找并不抛异常的实现

>>2020,微服务装逼指南

Java 枚举查找并不抛异常的实现


Java Enum是一个非常有用的功能,但很多人通常并不能充分利用,这是因为一些库不会优先择用该功能。通常我们也可以正确使用Java枚举功能,但在许多代码库中往往存在着这样一个问题,于是有了这篇文章。问题很简单:我们应该如何通过名称或值获取枚举,并忽略不存在的值?

枚举

这是我们将在示例中使用的枚举。挑选更复杂的枚举是为了也可以通过其他字段展示查找枚举。

public enum CardColor {
RED,
BLACK,
;
}
// Jackson annotation to print the enum as an Object instead of the default name.
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum CardSuit {
// Unicode suits - https://en.wikipedia.org/wiki/Playing_cards_in_Unicode
SPADE("Spade", String.valueOf((char) 0x2660), CardColor.BLACK),
HEART("Heart", String.valueOf((char) 0x2665), CardColor.RED),
DIAMOND("Diamond", String.valueOf((char) 0x2666), CardColor.RED),
CLUB("Club", String.valueOf((char) 0x2663), CardColor.BLACK),
;
private String displayName;
private String symbol;
private CardColor color;
private CardSuit(String displayName, String symbol, CardColor color) {
this.displayName = displayName;
this.symbol = symbol;
this.color = color;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public CardColor getColor() {
return color;
}
public void setColor(CardColor color) {
this.color = color;
}

在 GitHub 上查看。

问题

在你知道输入有效的时候,使用Enum.valueOf非常棒。但是,如果传入无效的名称,那么将抛出异常。在某些情况下,这很好。不过,在通常情况下,我们宁愿忽略异常并返回null。

log.debug("Running valueOf");
for (String name : names) {
try {
log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.valueOf(name)));
} catch (Exception ex) {
log.warn("Exception Thrown", ex);
}
}

 GitHub 上查看。

2017-02-22 14:46:38.556 [main] DEBUG c.s.examples.common.EnumLookup - Running valueOf
2017-02-22 14:46:38.804 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"}
2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"}
2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"}
2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"}
2017-02-22 14:46:38.808 [main] WARN c.s.examples.common.EnumLookup - Exception Thrown
java.lang.IllegalArgumentException: No enum constant com.stubbornjava.examples.common.EnumLookup.CardSuit.Missing
at java.lang.Enum.valueOf(Enum.java:238)
at com.stubbornjava.examples.common.EnumLookup$CardSuit.valueOf(EnumLookup.java:1)
at com.stubbornjava.examples.common.EnumLookup.main(EnumLookup.java:154)

拙劣的实现

很不幸的是,以下两种方法在代码库中出现得是这么的频繁。反面例子,勿学。

Enum.valueOf With Try Catch(劣)

这种拙劣的做法最常见于初学者。异常不应该用于控制流,并且这样可能会有一些性能影响。不要偷懒。你必须用正确的方式去做。

/*
* Please don't do this! Using try / catch for
* control flow is a bad practice.
*/

public static CardSuit trycatchValueOf(String name) {
try {
return CardSuit.valueOf(name);
} catch (Exception ex) {
log.warn("Exception Thrown", ex);
return null;
}
}

 GitHub 上查看。

log.debug("Running trycatchValueOf");
for (String name : names) {
log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.trycatchValueOf(name)));
}

 GitHub 上查看。

2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - Running trycatchValueOf
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"}
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"}
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"}
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"}
2017-02-22 14:46:38.809 [main] WARN c.s.examples.common.EnumLookup - Exception Thrown
java.lang.IllegalArgumentException: No enum constant com.stubbornjava.examples.common.EnumLookup.CardSuit.Missing
at java.lang.Enum.valueOf(Enum.java:238)
at com.stubbornjava.examples.common.EnumLookup$CardSuit.valueOf(EnumLookup.java:1)
at com.stubbornjava.examples.common.EnumLookup$CardSuit.trycatchValueOf(EnumLookup.java:89)
at com.stubbornjava.examples.common.EnumLookup.main(EnumLookup.java:171)
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null

通过迭代查找(劣)

这种方法也很常见(见这里),但至少程序员知道不能用try/catch来捕获异常。那么,这种方法有什么问题呢?没错,它会迭代所有枚举,直到找到匹配的枚举或返回null——最坏的情况下需要n次,其中n就是枚举值的数量。有些人可能会认为这微不足道,这是过早优化了而已。但是,数据结构和算法是CS基础。使用Map而不是迭代集合要省力得多。这会大大提高性能吗?不,但它是一个很好的习惯。在面试候选人时,你会对线性复杂度搜索算法感到满意吗?此时,你不应该让这样的代码审查通过。

/*
* Please don't do this! It is inefficient and it's
* not very hard to use Guava or a static Map as an index.
*/

public static CardSuit iterationFindByName(String name) {
for (CardSuit suit : CardSuit.values()) {
if (name.equals(suit.name())) {
return suit;
}
}
return null;
}

 GitHub 上查看。

log.debug("Running iteration");
for (String name : names) {
log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.iterationFindByName(name)));
}

 GitHub 上查看。

2017-02-22 14:46:38.808 [main] DEBUG c.s.examples.common.EnumLookup - Running iteration
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"}
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"}
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"}
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"}
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null

较优的实现

以下都可以通过使用Map形式的索引起作用。但是,它们之间也有一些细微的差别。

静态Map索引(较优)

用于快速查找固定大小的正确数据结构是什么?那就是HashMap。现在通过一些额外的样板,只要我们有很好的散列函数的话,我们就可以进行更有效的查找。稍微更冗长,但如果有办法减少样板的话,这将是极好的。

private static final Map<String, CardSuit> nameIndex =
Maps.newHashMapWithExpectedSize(CardSuit.values().length);
static {
for (CardSuit suit : CardSuit.values()) {
nameIndex.put(suit.name(), suit);
}
}
public static CardSuit lookupByName(String name) {
return nameIndex.get(name);
}

 GitHub 上查看。

log.debug("Running lookupByName");
for (String name : names) {
log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.lookupByName(name)));
}

 GitHub 上查看。

2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - Running lookupByName
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"}
2017-02-22 14:46:38.810 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"}
2017-02-22 14:46:38.810 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"}
2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"}
2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null

Guava Enums.getIfPresent(推荐)

这是一个常见的用例,我们在Google的朋友为此提供了一个非常干净且无需样板的解决方案。探其究竟,它甚至使用了WeakReferences和WeakHashMaps。基本说来,这段代码将创建一个全局的静态地图,并以Enum的类名称键入,并将其用于查找。

public static CardSuit getIfPresent(String name) {
return Enums.getIfPresent(CardSuit.class, name).orNull();
}

 GitHub 上查看。

log.debug("Running Guava getIfPresent");
for (String name : names) {
log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.getIfPresent(name)));
}

 GitHub 上查看。

2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup - Running Guava getIfPresent
2017-02-22 14:46:38.814 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"}
2017-02-22 14:46:38.814 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"}
2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"}
2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"}
2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null

通过字段的进一步索引

这个完全相同的方法可以用于枚举的其他字段。想要通过其显示的名称或其他属性来查找枚举并不少见。

通过字段索引的静态Map(较优)

与上述相同的方法,但是在显示名称上而不是枚举名称上进行索引。

private static final Map<String, CardSuit> displayNameIndex =
Maps.newHashMapWithExpectedSize(CardSuit.values().length);
static {
for (CardSuit suit : CardSuit.values()) {
displayNameIndex.put(suit.getDisplayName(), suit);
}
}
public static CardSuit lookupByDisplayName(String name) {
return displayNameIndex.get(name);
}

 GitHub 上查看。

log.debug("Running lookupByDisplayName");
for (String displayName : displayNames) {
log.debug("looking up {} found {}", displayName, Json.serializer().toString(CardSuit.lookupByDisplayName(displayName)));
}

 GitHub 上查看。

2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - Running lookupByDisplayName
2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up Spade found {"displayName":"Spade","symbol":"♠","color":"BLACK"}
2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up Heart found {"displayName":"Heart","symbol":"♥","color":"RED"}
2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up Diamond found {"displayName":"Diamond","symbol":"♦","color":"RED"}
2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Club found {"displayName":"Club","symbol":"♣","color":"BLACK"}
2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null

通过字段索引的静态Map(较优)

我们不能在这里利用Guava,因为对于静态索引创建唯一的全局密钥将是一件困难的事。但是,这并不意味着我们没有帮手!

public class EnumUtils {
public static <T, E extends Enum<E>> Function<T, E> lookupMap(Class<E> clazz, Function<E, T> mapper) {
@SuppressWarnings("unchecked")
E[] emptyArray = (E[]) Array.newInstance(clazz, 0);
return lookupMap(EnumSet.allOf(clazz).toArray(emptyArray), mapper);
}
public static <T, E extends Enum<E>> Function<T, E> lookupMap(E[] values, Function<E, T> mapper) {
Map<T, E> index = Maps.newHashMapWithExpectedSize(values.length);
for (E value : values) {
index.put(mapper.apply(value), value);
}
return (T key) -> index.get(key);
}
}

 GitHub 上查看。

现在我们有了一个相与样板没多大关联的通用解决方案。

private static final Function<String, CardSuit> func =
EnumUtils.lookupMap(CardSuit.class, e -> e.getDisplayName()
);
public static CardSuit lookupByDisplayNameUtil(String name) {
return func.apply(name);
}

 GitHub 上查看。

log.debug("Running lookupByDisplayNameUtil");
for (String displayName : displayNames) {
log.debug("looking up {} found {}", displayName, Json.serializer().toString(CardSuit.lookupByDisplayNameUtil(displayName)));
}

 GitHub 上查看。

2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - Running lookupByDisplayNameUtil
2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Spade found {"displayName":"Spade","symbol":"♠","color":"BLACK"}
2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Heart found {"displayName":"Heart","symbol":"♥","color":"RED"}
2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Diamond found {"displayName":"Diamond","symbol":"♦","color":"RED"}
2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Club found {"displayName":"Club","symbol":"♣","color":"BLACK"}
2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null

结论

这里有若干方法都可用于解决同一个问题。有些拙劣,有些更优。

译文链接:http://www.codeceo.com/article/java-enum-lookup-no-exception.html
英文原文:Java Enum Lookup by Name or Field Without Throwing Exceptions





- THE END -


作者简介

Java 枚举查找并不抛异常的实现

Mr.W

白天搬砖,晚上砌梦想。

相信每个人有故事,程序员更是有许多事故,书写最接地气的程序员故事,为大家找出更好的资料。

Java 枚举查找并不抛异常的实现


原文始发于微信公众号(JAVA的学习之路):Java 枚举查找并不抛异常的实现