Java-枚举-逻辑循环参考 [英] Java - Enums - Logical circular reference

查看:96
本文介绍了Java-枚举-逻辑循环参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象下面的例子:

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.

是否有一种方法可以处理Java中的此类前向引用?

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?

推荐答案

在定义之前,不能将剪刀分配给 ROCK 。您可以改为在静态块中分配值。

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

我看到了很多例子,人们在构造函数中使用String值,但这是更具体的分配方法声明后的实际值。对此进行了封装,并且 beats 实例变量无法更改(除非使用反射)。

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());
        }
    }
}

输出

ROCK beats SCISSORS
PAPER beats ROCK
SCISSORS beats PAPER

这篇关于Java-枚举-逻辑循环参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆