gpt4 book ai didi

java - 在运行时设置 ENUM 值

转载 作者:行者123 更新时间:2023-12-01 13:49:01 26 4
gpt4 key购买 nike

我有一个 ENUM 定义为;

public enum YesNoEnum {
Y,
N
}

我将其用于我投票的值(value)观之一。

所以我在循环中使用它(从查询响应中循环对象数组)

person.setVoted(responseArray[1] != null ? YesNoEnum.valueOf((String)responseArray[1]) : null);

我有 setter 作为

public void setVoted(YesNoEnum voted) {
this.voted = voted;
}

现在,如果 responseArray[1] 的值为 Y/N

如果我 debug/watch responseArray[1] ,它会将类型显示为 YesNoEnum 并将值显示为 "Y"它说

cannot cast an instance of YesNoEnum to an instance of String

最佳答案

If I debug/watch responseArray[1] , it shows type as YesNoEnum and shows value as "Y" It says

如果我理解正确,responseArray 是枚举YesNoEnum 的数组。

因此,将枚举实例转换为字符串时会出现错误:

(String)responseArray[1]

你可以这样写:

person.setVoted(responseArray[1]);

作为旁注

要处理null,我会将枚举更改为:

public enum YesNoEnum {
Y,
N,
UNKNOWN
}

并写:

person.setVoted(responseArray[1] != null ? responseArray[1] : YesNoEnum.UNKNOWN);

关于java - 在运行时设置 ENUM 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20117456/

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