gpt4 book ai didi

java - Guava getIfPresent() 返回错误

转载 作者:行者123 更新时间:2023-12-02 11:08:36 25 4
gpt4 key购买 nike

我正在尝试使用 guava 的 getIfPresent() 进行枚举,如下所示:

private enum LegalColumns
{

PRODUCERS_CUT("PRODUCER'S CUT", PMCColumnsEnum.NETWORK_CUT_1.getColumnName()),
PROPOSED_LOCKED_CUT("PROPOSED LOCKED CUT", PMCColumnsEnum.NETWORK_CUT_3.getColumnName()),
LOCK("LOCK", PMCColumnsEnum.LOCKED_DELIVERY.getColumnName()),
FINAL_MIX("FINAL MIX", PMCColumnsEnum.MIX_DATE.getColumnName());

private String column;
private String replacementColumn;

LegalColumns(String column, String replacementColumn) {
this.column = column;
this.replacementColumn = replacementColumn;
}


public static LegalColumns getIfPresent(String column) {
System.out.println(Enums.getIfPresent(LegalColumns.class, column.trim().toUpperCase()));
return Enums.getIfPresent(LegalColumns.class, column.toUpperCase()).orNull();
}
}

但是,当我单步执行此操作时,尽管字符串完全匹配,但它总是打印出 Optional.absent() 。据我所知,我完全遵循了 Guava 规范。我缺少什么想法吗?

最佳答案

https://google.github.io/guava/releases/15.0/api/docs/com/google/common/base/Enums.html#getIfPresent(java.lang.Class,%20java.lang.String)

Returns an optional enum constant for the given type, using Enum.valueOf(java.lang.Class, java.lang.String). If the constant does not exist, Optional.absent() is returned. A common use case is for parsing user input or falling back to a default enum constant. For example, Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);

https://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html?is-external=true#valueOf(java.lang.Class,%20java.lang.String)

Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

摘自您的评论

I have gone with another approach, but for others, I passed in columns like "FINAL MIX".

“最终混合”!=“FINAL_MIX”

Guava 使用枚举标识符,而不是传递到构造函数中的字符串。

因此,对于枚举实例,FINAL_MIX("FINAL MIX", PMCColumnsEnum.MIX_DATE.getColumnName()); 枚举标识符是“FINAL_MIX”,而不是您在“FINAL MIX”中传递的字符串

此外!由于您没有在 string.toUpperCase 上定义区域设置,因此您面临 turkey I bug 的风险.

关于java - Guava getIfPresent() 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com