返回枚举值而不调用 get 函数
在 Java 中是否可以返回 enum
值,而无需调用函数来返回该值,例如我的示例中的 getFlag()
?如果是这样,怎么办?
public enum MessageFlags {
BIT0((short)1),
BIT1((short)2),
BIT2((short)4),
BIT3((short)8),
BIT4((short)16),
BIT5((short)32),
BIT6((short)64),
BIT7((short)128),
BIT8((short)256),
BIT9((short)512),
BIT10((short)1024),
set_freq(BIT0),
get_freq(BIT1);
short bitFlag = 0;
MessageFlags flag;
MessageFlags(short flag) {
this.bitFlag = flag;
}
MessageFlags(MessageFlags flag) {
this.flag = flag;
}
public short getFlag() {
return this.flag.bitFlag;
}
public short getValue() {
return this.bitFlag;
}
}
Is it possible in Java to return the enum
value without having to call a function to return the value, such as getFlag()
in my example? If so, how?
public enum MessageFlags {
BIT0((short)1),
BIT1((short)2),
BIT2((short)4),
BIT3((short)8),
BIT4((short)16),
BIT5((short)32),
BIT6((short)64),
BIT7((short)128),
BIT8((short)256),
BIT9((short)512),
BIT10((short)1024),
set_freq(BIT0),
get_freq(BIT1);
short bitFlag = 0;
MessageFlags flag;
MessageFlags(short flag) {
this.bitFlag = flag;
}
MessageFlags(MessageFlags flag) {
this.flag = flag;
}
public short getFlag() {
return this.flag.bitFlag;
}
public short getValue() {
return this.bitFlag;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需输入
MessageFlags.BITX
即可返回与getFlag()
相同的值Just say
MessageFlags.BITX
and that will return the same value asgetFlag()
您可以
导入静态 MessageFlags.*;
并说出BITX.getFlag()
。这是一个完整的示例:
A.java
B.java
You can
import static MessageFlags.*;
and sayBITX.getFlag()
.Here is a complete example:
A.java
B.java
我遵循了 @Jeremy 的建议:
然后在我的
MessageFlags
枚举中创建了一个名为set_freq
的方法。我将此函数设置为静态
,并让它返回short
。例如,set_freqflag
的语义有点奇怪,因为您没有设置任何内容,但我目前没有更好的名称。这允许我只声明set_freqflag()
而不是我之前所做的更长的方式。I followed @Jeremy's advice of this:
and then I created a method called
set_freq
in myMessageFlags
enum. I made this functionstatic
and had it returnshort
. For example,The semantics of
set_freqflag
are a little weird because you are not setting anything but I do not have a better name at the moment. This allows me to just stateset_freqflag()
rather than the longer way I was doing before.我可能真的迟到了,但我正在写信给访问此主题的任何人寻求帮助。
如果您有一个枚举,并且希望默认返回其值的特定参数而不调用 get 函数,则需要在所选函数上方插入 @Override,例如:
现在您可以调用您想要的任何枚举值'd like,没有 get 函数:
它会返回“sweet”
PS 我不是专业程序员,如果我不小心写了一些反传统的东西,请纠正我。
I might be really late, but I'm writing to anyone who visits this topic for help.
If you have an enum, and you'd like to return a specific parameter of its values by default without calling a get function, you need to insert an @Override above your selected function, like:
And now you can call whichever enum value you'd like, without a get function:
And it'll return "sweet"
P.S. I'm not a professional programmer, please correct me if I've written something anti-conventional by accident.