Java - Enums - Logical circular reference [duplicate]

我只是一个虾纸丫 提交于 2019-12-23 21:41:09

问题


Imagine the following made up example:

public enum Hand {
  ROCK(SCISSORS),
  PAPER(ROCK),
  SCISSORS(PAPER);

  private final Hand beats;

  Hand(Hand beats) {
    this.beats = beats;
  }
}

I will get an error Illegal forward reference for forward referencing SCISSORS.


Is there a way to handle such forward references in Java?

Or how would you model such a situation, where you have a logical circular reference between several enums values?


回答1:


You cannot assign SCISSORS to ROCK before it is defined. You can, instead, assign the values in a static block.

I have seen a lot examples where people use String values in the constructors, but this is more concrete to assign the actual values after they have been declared. This is encapsulated and the beats instance variable cannot be changed (unless you use reflection).

public enum Hand {
    ROCK,
    PAPER,
    SCISSORS;

    private Hand beats;

    static {
        ROCK.beats = SCISSORS;
        PAPER.beats = ROCK;
        SCISSORS.beats = PAPER;
    }

    public Hand getBeats() {
        return beats;
    }

    public static void main(String[] args) {
        for (Hand hand : Hand.values()) {
            System.out.printf("%s beats %s%n", hand, hand.getBeats());
        }
    }
}

Output

ROCK beats SCISSORS
PAPER beats ROCK
SCISSORS beats PAPER


来源:https://stackoverflow.com/questions/41242471/java-enums-logical-circular-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!