java - 如何从java对象加载Enum

标签 java enums enumeration

我正在研究 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/

相关文章:

javascript - 为 JavaScript 对象编写枚举器

java - 如何在 Java 中创建一个包含字符串、字符串数组和 int 数组的对象?

java - 未处理的异常,但 try catch block 似乎没有做我认为应该做的事情

java - 在 JPA 中从集合中的枚举搜索时类型错误

matlab - 遍历矩阵列的最佳方法是什么?

c# - LINQ 和枚举

java - JFrame 很小

java - 在 zookeeper 中创建路径的最有效方法,其中路径的根元素可能存在也可能不存在?

syntax - 有没有办法在 Kotlin 的数据类中嵌套枚举?

java - 不同类型单位的抽象类