【问题标题】:Why are constants in Java the way they are?为什么Java中的常量是这样的?
【发布时间】:2011-04-23 19:50:15
【问题描述】:

我已经阅读过 Java 枚举并经常使用它们。但是,我不明白为什么 JFrame.EXIT_ON_CLOSE 会返回 int

考虑http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html

// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL   = 3;

不是类型安全的 - 由于季节只是一个 int,因此您可以在需要季节的任何其他 int 值中传递,或者将两个季节相加(这没有意义)。

JFrame.EXIT_ON_CLOSE返回3,而JFrame.HIDE_ON_CLOSE返回1,这意味着后者的三个等于第一个。

为什么要这样实现?

【问题讨论】:

    标签: java enums constants


    【解决方案1】:

    Java 没有枚举 until 1.5 - 这些常量中的大部分都是之前引入的,如果将它们更改为枚举,Sun 会破坏很多现有代码。

    【讨论】:

    • 在 Swing 的其他地方,枚举“模式”在没有语言支持的情况下使用。
    【解决方案2】:

    这些常量可能是在枚举添加到语言之前添加到标准库中的。在Java 1.5 中添加了枚举。为了保持向后兼容性,他们保留了原来的常量。

    【讨论】:

      【解决方案3】:

      枚举是最近添加到 Java 中的。将所有旧的整数常量更改为枚举会破坏很多现有的 Java 代码。

      【讨论】:

        【解决方案4】:

        你提供的链接说:

        In prior releases, the standard way to represent an enumerated type was
        the int Enum pattern:
        
        // int Enum Pattern - has severe problems!
        public static final int SEASON_WINTER = 0;
        public static final int SEASON_SPRING = 1;
        etc...
        

        Java Swing (JFrame) 早得多。

        【讨论】:

          猜你喜欢
          • 2011-10-04
          • 2010-12-31
          • 1970-01-01
          • 2023-02-13
          • 1970-01-01
          • 1970-01-01
          • 2020-08-22
          • 2019-11-13
          • 1970-01-01
          相关资源
          最近更新 更多