我正在研究 Java。请检查下面我的代码:
TestEnum.java
public class TestEnum
{
public enum AccountState {
NEW("new"), OLD("old")
}
}
MyMain.java
public class MyMain
{
public static void main(String args[])throws Exception {
//working fine
System.out.println(TestEnum.AccountState.NEW);
// But When I create object for TestEnum by using new ,It's throw error message
System.out.println(new TestEnum().AccountState.NEW);
}
}
我遇到以下错误
AccountState 无法解析或不是字段 任何人都可以纠正我在代码中做错的事情。
最佳答案
(只需在 @StefanBeike 的答案之上添加一些更多信息)。
根据JLS §8.9 :
Nested enum types are implicitly static. It is permissible to explicitly declare a nested enum type to be static.
因此您可以使用以下方式引用它:
System.out.println(TestEnum.AccountState.NEW);
关于java - 如何从java对象加载Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756353/